<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>润色智能体</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
        /* 添加黑夜模式样式 */
        :root {
            --bg-color: #f9f9f9;
            --text-color: #333;
            --card-bg: white;
            --card-border: #e0e0e0;
            --card-shadow: rgba(0,0,0,0.1);
            --user-msg-bg: #e7f7ff;
            --ai-msg-bg: white;
            --input-bg: white;
            --btn-primary: #4CAF50;
            --btn-hover: #45a049;
            --btn-text: white;
            --legend-bg: white;
            --keyword-border: #e0e0e0;
            --keyword-active-bg: #f0f7ff;
            --keyword-active-color: #1a73e8;
            --keyword-active-border: #1a73e8;
            --action-btn-bg: white;
            --action-btn-border: #ddd;
            --action-btn-color: #666;
            --action-btn-hover: #f5f5f5;
            --gradient-start: rgba(249,249,249,1);
            --gradient-end: rgba(249,249,249,0);
            --msg-text-color: #333;
            --msg-del-color: #ff0000;
            --msg-del-bg: #ffe6e6;
            --msg-add-color: #0000ff;
            --msg-add-bg: #e6f3ff;
            --msg-modify-bg: #e6ffe6;
            --msg-modify-color: #006400;
        }

        body.dark-mode {
            --bg-color: #1a1a1a;
            --text-color: #e0e0e0;
            --card-bg: #2d2d2d;
            --card-border: #444;
            --card-shadow: rgba(0,0,0,0.3);
            --user-msg-bg: #2c4356;
            --ai-msg-bg: #2d2d2d;
            --input-bg: #2d2d2d;
            --btn-primary: #388e3c;
            --btn-hover: #2e7d32;
            --btn-text: #e0e0e0;
            --legend-bg: #2d2d2d;
            --keyword-border: #444;
            --keyword-active-bg: #1c3a5e;
            --keyword-active-color: #90caf9;
            --keyword-active-border: #90caf9;
            --action-btn-bg: #2d2d2d;
            --action-btn-border: #444;
            --action-btn-color: #aaa;
            --action-btn-hover: #3d3d3d;
            --gradient-start: rgba(26,26,26,1);
            --gradient-end: rgba(26,26,26,0);
            --msg-text-color: #e0e0e0;
            --msg-del-color: #ff6b6b;
            --msg-del-bg: #442222;
            --msg-add-color: #6b8cff;
            --msg-add-bg: #1a2b3d;
            --msg-modify-bg: #1a4422;
            --msg-modify-color: #90ff90;
        }

        /* 应用变量到现有样式 */
        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: auto;
            overflow-x: hidden;
        }

        /* 进一步优化消息区域布局，保持整体左中右结构 */
        .main-content {
            margin-left: 60px;
            width: calc(100% - 60px); /* 仅考虑左侧导航栏 */
            transition: margin-left 0.3s ease, width 0.3s ease;
            position: relative;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* 确保树显示时的布局依然正确 */
        .main-content.tree-visible {
            margin-right: 300px;
            width: calc(100% - 360px); /* 60px左侧导航栏 + 300px右侧树 */
        }

        /* 重新定义原始样式 */
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 1000px;
            margin: 0 auto;
            width: 100%;
            position: relative;
            height: calc(100vh - 100px);
            padding: 0 5px; /* 添加最小边距 */
            overflow: hidden;
            box-sizing: border-box; /* 确保边距计算正确 */
        }

        .chat-messages {
            flex: 1;
            padding: 20px 5px; /* 减小水平内边距 */
            display: flex;
            flex-direction: column;
            gap: 16px;
            scroll-behavior: smooth;
            padding-bottom: 400px !important;
            opacity: 0;
            transition: opacity 0.5s ease-in-out;
            overflow-y: auto;
            height: 100%;
            position: relative;
            width: 100%;
            box-sizing: border-box; /* 确保边距计算正确 */
        }

        .chat-messages.visible {
            opacity: 1;
        }

        /* 完全重定义消息样式 */
        .message {
            position: relative;
            padding: 16px;
            border-radius: 10px;
            margin-bottom: 30px; /* 消息底部间距 */
            line-height: 1.5;
            word-break: break-word;
            white-space: pre-wrap;
            overflow-wrap: break-word;
            max-width: 85%; /* 最大宽度 */
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        /* AI消息样式 */
        .message-left {
            align-self: flex-start;
            margin-right: auto;
            margin-left: 0;
            background-color: var(--ai-msg-bg);
            border: 1px solid var(--card-border);
            box-shadow: 0 1px 2px var(--card-shadow);
            width: fit-content;
            min-width: 200px;
            border-top-left-radius: 4px; /* 左上角更尖锐 */
        }

        /* 用户消息样式 */
        .message-right {
            align-self: flex-end;
            margin-left: auto;
            margin-right: 0; /* 确保贴近右侧 */
            background-color: var(--user-msg-bg);
            border: none;
            box-shadow: 0 1px 2px var(--card-shadow);
            width: fit-content;
            min-width: 200px;
            border-top-right-radius: 4px; /* 右上角更尖锐 */
        }

        .message-sender {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 12px;
            opacity: 0.8;
        }

        .message-content {
            word-wrap: break-word;
            white-space: pre-wrap;
            margin: 12px 0;
            font-size: 15px;
            color: var(--msg-text-color);
            overflow-wrap: break-word;
            word-break: break-word;
        }

        .message-marker {
            position: absolute;
            top: 8px;
            right: 8px;
            font-size: 12px;
            color: var(--text-color);
            opacity: 0.7;
        }

        /* 调整输入区域布局 */
        .input-area {
            position: fixed;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            max-width: 1000px; /* 匹配聊天容器宽度 */
            background: transparent;
            padding: 20px 0; /* 移除水平内边距 */
            z-index: 1000;
            transition: all 0.5s ease-in-out;
            top: 50%;
        }

        .input-area.moved {
            transform: translate(-50%, 0);
            top: auto;
            bottom: 0;
            background: transparent;
            padding-top: 100px;
            padding-bottom: 20px;
            pointer-events: none;
            width: 100%;
            max-width: 1000px; /* 匹配聊天容器宽度 */
        }

        .input-container {
            max-width: 720px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 10px;
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 2px 10px var(--card-shadow);
            padding: 12px;
            border: 1px solid var(--card-border);
            position: relative;
            overflow: hidden;
            pointer-events: auto; /* 恢复输入容器内的点击事件 */
        }

        .input-container textarea {
            width: 100%;
            min-height: 24px;
            max-height: 200px;
            padding: 8px 8px 40px 8px;
            border: none;
            border-radius: 8px;
            resize: none;
            font-size: 16px;
            background: var(--input-bg);
            outline: none;
            overflow-y: auto;
            box-sizing: border-box;
            color: var(--text-color);
        }

        .style-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            padding: 8px 0;
            border-top: 1px solid var(--card-border);
            margin-top: 8px;
        }

        .keyword-btn {
            padding: 6px 12px;
            font-size: 13px;
            border: 1px solid var(--keyword-border);
            border-radius: 16px;
            background: var(--card-bg);
            color: var(--text-color);
            cursor: pointer;
            transition: all 0.2s;
        }

        .keyword-btn.active {
            background: var(--keyword-active-bg);
            color: var(--keyword-active-color);
            border-color: var(--keyword-active-border);
        }

        #submit {
            position: absolute;
            right: 12px;
            bottom: 12px;
            padding: 6px 16px;
            border-radius: 8px;
            background-color: var(--btn-primary);
            color: var(--btn-text);
            border: none;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 14px;
            z-index: 10;
        }

        #submit:hover {
            background-color: var(--btn-hover);
        }

        #submit:disabled {
            background-color: #cccccc;
        }

        .container, .text-area, .keywords, 
        textarea:not(.input-container textarea), 
        #output, .header, .description {
            display: none;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .text-area {
            margin: 20px 0;
            position: relative;
        }
        .keywords {
            margin: 10px 0;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .keyword-btn {
            padding: 5px 15px;
            border: 2px solid #4CAF50;
            border-radius: 20px;
            background: white;
            color: #4CAF50;
            cursor: pointer;
            transition: all 0.3s;
        }
        .keyword-btn.active {
            background: #4CAF50;
            color: white;
        }
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            min-height: 150px;
            resize: vertical;
        }
        #output {
            border: 1px solid #ddd;
            padding: 15px;
            min-height: 150px;
            border-radius: 4px;
            background-color: #fff;
            line-height: 1.6;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .loading {
            display: none;
            margin-left: 10px;
            color: #666;
        }
        del {
            color: var(--msg-del-color);
            text-decoration: line-through;
            background-color: var(--msg-del-bg);
            padding: 0 2px;
        }
        span[style*="color: blue"] {
            color: var(--msg-add-color) !important;
            background-color: var(--msg-add-bg) !important;
            padding: 0 2px;
            font-weight: bold;
        }
        span[style*="background-color: #90EE90"] {
            background-color: var(--msg-modify-bg) !important;
            color: var(--msg-modify-color) !important;
            padding: 0 2px;
            font-weight: bold;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .description {
            color: #666;
            margin-bottom: 20px;
        }
        .typing-cursor {
            display: inline-block;
            width: 2px;
            height: 1em;
            background-color: #000;
            margin-left: 2px;
            animation: blink 1s infinite;
        }

        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0; }
        }

        #output span, #output del {
            display: inline;
        }
        
        .clickable {
            cursor: pointer;
        }
        
        .clickable:hover {
            opacity: 0.8;
        }
        
        .selection-tip {
            display: none;
            position: fixed;
            background: #333;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 1000;
            pointer-events: none;
            white-space: nowrap;
        }

        /* 添加图例样式 */
        .legend {
            position: fixed;
            left: 310px; /* 与左侧思维导图对齐 */
            bottom: 20px;
            background: var(--card-bg);
            padding: 12px;
            border-radius: 8px;
            box-shadow: 0 2px 8px var(--card-shadow);
            z-index: 99;
            font-size: 12px;
            transition: left 0.3s ease;
            border: 1px solid var(--card-border);
            color: var(--text-color);
            width: 250px;
        }

        .legend-title {
            font-weight: bold;
            margin-bottom: 10px;
            font-size: 14px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            margin: 5px 0;
            font-size: 13px;
        }

        .legend-sample {
            display: inline-block;
            margin-right: 8px;
            padding: 2px 8px;
        }

        .legend-delete {
            color: #ff0000;
            text-decoration: line-through;
            background-color: #ffe6e6;
        }

        .legend-add {
            color: blue;
            font-weight: bold;
        }

        .legend-modify {
            background-color: #90EE90;
        }

        /* 修改撤回按钮样式 */
        .undo-btn {
            position: absolute;
            right: 0;
            top: -40px;  /* 移动到上方 */
            background: white;
            border: 1px solid #ddd;
            cursor: pointer;
            padding: 8px;
            border-radius: 4px;  /* 改为方形圆角 */
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;  /* 图标和文字之间的间距 */
        }

        .undo-btn:hover {
            background-color: #f5f5f5;
            border-color: #ccc;
        }

        .undo-btn svg {
            width: 16px;
            height: 16px;
            fill: #666;
        }

        .undo-btn span {
            font-size: 13px;
            color: #666;
        }

        .undo-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* 适配移动端 */
        @media (max-width: 768px) {
            .chat-container {
                max-width: 100%;
            }
            
            .input-area {
                max-width: 100%;
                padding: 10px;
            }
            
            .input-container {
                max-width: 100%;
            }
            
            .message {
                max-width: 90%;
            }
            
            .legend {
                left: 70px;
            }
            
            .sidebar.open + .main-content .legend {
                left: 190px;
            }
        }

        /* 修改水印样式 */
        body::before {
            content: '润色智能体';
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: rgba(0, 0, 0, 0.02);
            font-size: 192px; /* 增大一倍 */
            font-weight: bold;
            white-space: nowrap;
            pointer-events: none;
            z-index: 0;
            font-family: "宋体", SimSun, serif; /* 改为宋体 */
            text-shadow: none; /* 移除阴影 */
        }

        /* 修改复制按钮样式 */
        .copy-button, .message:hover .copy-button, .copy-button:hover {
            display: none;
        }

        /* 修改消息气泡操作按钮 */
        .message-actions {
            position: absolute;
            bottom: -40px;
            right: 0;
            display: flex;
            gap: 8px;
            opacity: 0;
            transition: opacity 0.3s;
            z-index: 5;
            pointer-events: auto; /* 确保操作按钮可点击 */
        }

        .message:hover .message-actions {
            opacity: 1;
        }

        .action-button {
            background: var(--action-btn-bg);
            border: 1px solid var(--action-btn-border);
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            color: var(--action-btn-color);
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .action-button:hover {
            background-color: var(--action-btn-hover);
        }

        .action-button svg {
            width: 14px;
            height: 14px;
            display: inline-block !important;
        }

        /* 修改导航栏结构，添加底部容器和移动主题切换按钮 */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 60px;
            height: 100vh;
            background-color: var(--card-bg);
            border-right: 1px solid var(--card-border);
            display: flex;
            flex-direction: column;
            transition: width 0.3s ease;
            z-index: 100;
        }

        .sidebar:hover {
            width: 180px;
        }

        .nav-header {
            padding: 0 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid var(--card-border);
            height: 50px;
            box-sizing: border-box;
            padding-top: 28px;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            height: 100%;
            padding-left: 10px;
        }

        .logo-icon {
            width: 32px;
            height: 32px;
            background-color: #4CAF50;
            color: white;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            font-weight: bold;
            flex-shrink: 0;
        }

        .logo-text {
            font-size: 16px;
            font-weight: bold;
            color: var(--text-color);
            opacity: 0;
            transition: opacity 0.3s ease;
            white-space: nowrap;
            margin-left: 10px;
            display: flex;
            align-items: center;
            height: 100%;
            padding-top: 0;
        }

        .sidebar:hover .logo-text {
            opacity: 1;
        }

        .mobile-menu-toggle {
            display: none;
            cursor: pointer;
        }

        .nav-items {
            flex: 1;
            padding: 20px 0;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .nav-bottom {
            padding: 20px 0;
            border-top: 1px solid var(--card-border);
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .nav-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-radius: 8px;
            color: var(--text-color);
            text-decoration: none;
            transition: background-color 0.3s ease;
        }

        .nav-item:hover {
            background-color: var(--keyword-active-bg);
        }

        .nav-icon {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .nav-text {
            margin-left: 10px;
            font-size: 14px;
            opacity: 0;
            transition: opacity 0.3s ease;
            white-space: nowrap;
        }

        .sidebar:hover .nav-text {
            opacity: 1;
        }

        .theme-toggle-nav {
            margin-top: auto;
        }

        /* 主内容区域居中调整 */
        .main-content {
            margin-left: 60px;
            width: calc(100% - 60px); /* 仅考虑左侧导航栏 */
            transition: margin-left 0.3s ease, width 0.3s ease;
            position: relative;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* 确保树显示时的布局依然正确 */
        .main-content.tree-visible {
            margin-right: 300px;
            width: calc(100% - 360px); /* 60px左侧导航栏 + 300px右侧树 */
        }

        .sidebar:hover ~ .legend {
            left: 430px; /* 180px + 250px */
        }

        .logo {
            margin-bottom: 30px;
            font-weight: bold;
            font-size: 18px;
            color: var(--text-color);
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            padding: 0 10px;
            white-space: nowrap;
            overflow: hidden;
        }

        .logo-icon {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            background-color: var(--btn-primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            margin-right: 10px;
            flex-shrink: 0;
        }

        .logo-text {
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .sidebar:hover .logo-text {
            opacity: 1;
        }

        .nav-items {
            flex: 1;
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .nav-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-radius: 8px;
            margin: 0 10px;
            cursor: pointer;
            transition: all 0.2s ease;
            color: var(--text-color);
            text-decoration: none;
            white-space: nowrap;
            overflow: hidden;
        }

        .nav-item:hover, .nav-item.active {
            background-color: var(--keyword-active-bg);
            color: var(--keyword-active-color);
        }

        .nav-icon {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .nav-text {
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .sidebar:hover .nav-text {
            opacity: 1;
        }

        /* 添加底部主题切换按钮 */
        .nav-bottom {
            width: 100%;
            margin-top: auto; /* 推到底部 */
            padding-bottom: 20px; /* 底部间距 */
        }

        .nav-item.theme-toggle-nav {
            display: flex;
            align-items: center;
            padding: 10px;
            border-radius: 8px;
            margin: 0 10px;
            cursor: pointer;
            transition: all 0.2s ease;
            color: var(--text-color);
            text-decoration: none;
            white-space: nowrap;
            overflow: hidden;
        }

        .nav-item.theme-toggle-nav:hover {
            background-color: var(--keyword-active-bg);
            color: var(--keyword-active-color);
        }

        .theme-toggle-nav .nav-icon {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .theme-toggle-nav .nav-icon svg {
            width: 20px;
            height: 20px;
            fill: currentColor;
        }

        .theme-toggle-nav .nav-text {
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .sidebar:hover .theme-toggle-nav .nav-text {
            opacity: 1;
        }

        /* 删除旧的主题切换按钮样式 */
        .theme-toggle {
            display: none;
        }

        /* 修改树容器样式 */
        .tree-container {
            position: fixed;
            right: 0;
            top: 0;
            width: 300px;
            height: 100vh;
            background-color: var(--card-bg);
            border-left: 1px solid var(--card-border);
            padding: 20px;
            z-index: 90;
            display: flex;
            flex-direction: column;
            align-items: center;
            overflow: hidden;
        }

        /* 当树显示时调整主内容区域 */
        .main-content.tree-visible {
            margin-right: 300px;
            width: calc(100% - 360px); /* 60px左侧导航栏 + 300px右侧树 */
        }

        /* 修改树的渲染位置 */
        .tree-container svg {
            width: 100%;
            height: calc(100vh - 100px);
            margin-top: 20px;
        }

        /* 确保树容器内的内容居中 */
        .tree-container .tree-title {
            width: 100%;
            text-align: center;
            margin-bottom: 20px;
        }

        /* 树节点样式优化 */
        .node circle {
            fill: var(--card-bg);
            stroke: var(--keyword-active-color);
            stroke-width: 2px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .node.active circle {
            fill: var(--keyword-active-bg);
            stroke-width: 3px;
        }

        .node:hover circle {
            fill: var(--keyword-active-bg);
        }

        .node text {
            font: 12px sans-serif;
            fill: var(--text-color);
            pointer-events: none;
            font-weight: bold;
        }

        .link {
            stroke: var(--card-border);
            stroke-width: 1.5;
            fill: none;
        }

        /* 添加树标题样式 */
        .tree-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 20px;
            color: var(--text-color);
            text-align: center;
        }

        .text-tree-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 20px;
            color: var(--text-color);
            text-align: center;
        }

        .message.highlight {
            animation: highlight 1s ease-in-out;
        }

        @keyframes highlight {
            0%, 100% { background-color: transparent; }
            50% { background-color: yellow; }
        }

        /* 添加节点激活时的脉动动画 */
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }

        /* 添加以下样式到 <style> 部分，用于树的缩放时的过渡效果 */
        .tree-container svg {
            transition: all 0.3s ease;
        }

        .node, .link {
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .node:hover circle {
            transition: fill 0.2s ease, stroke-width 0.2s ease;
        }

        /* 修改文字思维导图容器样式 */
        .text-tree-container {
            position: fixed;
            left: 60px;
            top: 0;
            width: 300px;
            height: 100vh;
            background: var(--card-bg);
            border-right: 1px solid var(--card-border);
            padding: 20px;
            overflow-y: auto;
            z-index: 90;
            transition: left 0.3s ease;
        }

        /* 当导航栏展开时调整思维导图位置 */
        .sidebar:hover ~ .main-content .text-tree-container {
            left: 180px;  /* 与展开后的导航栏宽度相同 */
        }

        /* 响应式布局调整 */
        @media (max-width: 1600px) {
            .tree-container {
                width: 400px;
            }
            
            .main-content.tree-visible {
                margin-right: 400px;
                width: calc(100% - 710px);
            }
        }

        @media (max-width: 1200px) {
            .text-tree-container {
                width: 200px;
            }
            
            .legend {
                left: 260px;
                width: 200px;
            }
            
            .main-content {
                margin-left: 260px;
                width: calc(100% - 260px);
            }
            
            .main-content.tree-visible {
                margin-right: 350px;
                width: calc(100% - 610px);
            }
            
            .tree-container {
                width: 350px;
            }
        }

        @media (max-width: 768px) {
            .text-tree-container {
                display: none;
            }
            
            .legend {
                left: 70px;
                width: auto;
            }
            
            .main-content {
                margin-left: 60px;
                width: calc(100% - 60px);
            }
            
            .main-content.tree-visible {
                margin-right: 0;
                width: calc(100% - 60px);
            }
            
            .tree-container {
                width: 100%;
                left: 60px;
                right: 0;
            }
        }

        /* 添加节点提示框样式 */
        .tree-tooltip {
            position: fixed; /* 使用固定位置 */
            max-width: 350px; /* 增加最大宽度 */
            padding: 15px;
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            z-index: 1010;
            display: none;
            pointer-events: none;
            font-size: 14px;
            color: var(--text-color);
            line-height: 1.5;
            overflow-y: visible; /* 不使用滚动 */
            max-height: none; /* 移除高度限制 */
            word-break: break-word;
            transform-origin: left top; /* 缩放起点 */
            transform: scale(1); /* 初始缩放 */
            transition: transform 0.2s ease; /* 添加过渡效果 */
        }

        /* 文字思维导图样式优化 */
        .text-tree-item {
            padding: 5px 10px;
            margin: 3px 0;
            border-radius: 5px;
            transition: all 0.2s ease;
            line-height: 1.4;
            border-left: 3px solid transparent;
            font: 12px sans-serif; /* 使左侧思维导图字体与右侧树字体样式相同 */
        }

        .text-tree-node-container {
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .text-tree-content {
            flex: 1;
            padding: 2px 0;
        }

        .text-tree-toggle {
            background: none;
            border: none;
            width: 20px;
            height: 20px;
            padding: 0;
            margin-right: 5px;
            color: var(--text-color);
            opacity: 0.7;
            cursor: pointer;
            border-radius: 3px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .text-tree-toggle:hover {
            background-color: var(--hover-bg);
            opacity: 1;
            transform: scale(1.1);
        }

        .text-tree-toggle svg {
            width: 14px;
            height: 14px;
            transition: transform 0.2s ease;
        }

        .text-tree-spacer {
            width: 20px;
            margin-right: 5px;
            display: inline-block;
        }

        .text-tree-children {
            margin-left: 10px;
            border-left: 1px dashed var(--card-border);
            padding-left: 5px;
        }

        .text-tree-item:hover {
            background-color: var(--hover-bg);
            border-left-color: var(--btn-primary);
        }

        .text-tree-item.active {
            background-color: var(--hover-bg);
            border-left-color: var(--btn-primary);
        }

        /* 禁用的思维导图项目样式 */
        .disabled-tree-item {
            opacity: 0.6;
            text-decoration: line-through;
            cursor: default;
        }

        .disabled-tree-item:hover {
            background-color: transparent;
            border-left-color: transparent;
        }

        /* 消息字数统计样式优化 */
        .message-stats {
            position: absolute;
            bottom: -22px;
            right: 5px;
            font-size: 12px;
            color: var(--text-color);
            opacity: 0.7;
            z-index: 5; /* 确保在最上层 */
        }

        /* 修改悬浮提示框样式 */
        .nav-item .legend-tooltip {
            display: none;
            position: absolute;
            left: 100%;
            top: 50%;  /* 改为垂直居中 */
            transform: translateY(-50%);  /* 添加垂直居中变换 */
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 2px 8px var(--card-shadow);
            z-index: 1000;
            min-width: 200px;
            margin-left: 10px;
            white-space: nowrap;
        }

        .nav-item:hover .legend-tooltip {
            display: block;
        }

        .legend-tooltip::before {
            content: '';
            position: absolute;
            left: -6px;
            top: 50%;  /* 改为垂直居中 */
            transform: translateY(-50%);  /* 添加垂直居中变换 */
            border-top: 6px solid transparent;
            border-bottom: 6px solid transparent;
            border-right: 6px solid var(--card-bg);
        }

        .legend-tooltip::after {
            content: '';
            position: absolute;
            left: -7px;
            top: 50%;  /* 改为垂直居中 */
            transform: translateY(-50%);  /* 添加垂直居中变换 */
            border-top: 6px solid transparent;
            border-bottom: 6px solid transparent;
            border-right: 6px solid var(--card-border);
        }

        .legend-tooltip .legend-title {
            font-weight: bold;
            margin-bottom: 8px;
            font-size: 14px;
            color: var(--text-color);
        }

        .legend-tooltip .legend-item {
            display: flex;
            align-items: center;
            margin: 5px 0;
            font-size: 12px;
            color: var(--text-color);
        }

        .legend-tooltip .legend-sample {
            display: inline-block;
            margin-right: 8px;
            padding: 2px 8px;
        }

        .legend-tooltip .legend-delete {
            color: #ff0000;
            text-decoration: line-through;
            background-color: #ffe6e6;
        }

        .legend-tooltip .legend-add {
            color: blue;
            font-weight: bold;
        }

        .legend-tooltip .legend-modify {
            background-color: #90EE90;
        }

        /* 删除原有的 legend 样式 */
        .legend {
            display: none;
        }

        /* 文件上传按钮样式 */
        .file-upload {
            position: absolute;
            left: 10px;
            bottom: 12px;
            display: flex;
            align-items: center;
        }
        
        .file-upload input[type="file"] {
            display: none;
        }
        
        .file-upload-btn {
            background: transparent;
            border: none;
            cursor: pointer;
            padding: 6px;
            border-radius: 8px;
            color: var(--text-color);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .file-upload-btn:hover {
            background-color: var(--action-btn-hover);
        }
        
        .file-upload-btn svg {
            width: 20px;
            height: 20px;
            fill: currentColor;
        }
        
        /* 文件信息显示样式 */
        .file-info {
            display: none;
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 8px;
            padding: 8px 12px;
            margin-bottom: 10px;
            font-size: 14px;
            position: relative;
        }
        
        .file-info-name {
            font-weight: bold;
            margin-right: 10px;
        }
        
        .file-info-size {
            color: var(--action-btn-color);
            font-size: 12px;
        }
        
        .file-remove-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: transparent;
            border: none;
            cursor: pointer;
            color: var(--action-btn-color);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 4px;
            border-radius: 50%;
        }
        
        .file-remove-btn:hover {
            background-color: var(--action-btn-hover);
        }
        
        .file-remove-btn svg {
            width: 16px;
            height: 16px;
        }
        
        /* 导出按钮样式 */
        .export-buttons {
            display: flex;
            gap: 8px;
            margin-top: 10px;
        }
        
        .export-btn {
            background-color: var(--card-bg);
            border: 1px solid var(--card-border);
            color: var(--text-color);
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .export-btn:hover {
            background-color: var(--action-btn-hover);
        }
        
        .export-btn svg {
            width: 14px;
            height: 14px;
            fill: currentColor;
        }
        
        /* 专业领域选择样式 */
        .domain-selector {
            margin-top: 8px;
            border-top: 1px solid var(--card-border);
            padding-top: 8px;
        }
        
        .domain-label {
            display: block;
            font-size: 13px;
            margin-bottom: 5px;
            color: var(--text-color);
        }
        
        .domain-dropdown {
            width: 100%;
            padding: 6px 8px;
            border: 1px solid var(--card-border);
            border-radius: 6px;
            background-color: var(--input-bg);
            color: var(--text-color);
            font-size: 14px;
        }
        
        .domain-dropdown option {
            background-color: var(--card-bg);
            color: var(--text-color);
        }

        /* 调整专业领域选择样式 */
        .domain-selector {
            margin-top: 8px;
            border-top: 1px solid var(--card-border);
            padding-top: 8px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .selector-group {
            display: flex;
            align-items: center;
            gap: 10px;
            flex: 1;
            min-width: 200px;
        }
        
        .domain-label, .style-label {
            font-size: 13px;
            color: var(--text-color);
            white-space: nowrap;
        }
        
        .domain-dropdown, .style-dropdown {
            flex: 1;
            padding: 6px 8px;
            border: 1px solid var(--card-border);
            border-radius: 6px;
            background-color: var(--input-bg);
            color: var(--text-color);
            font-size: 14px;
            min-width: 100px;
        }
        
        /* 修改文件上传按钮样式 */
        .file-upload {
            position: absolute;
            left: 10px;
            bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .file-upload input[type="file"] {
            display: none;
        }
        
        .file-upload-btn {
            background: transparent;
            border: none;
            cursor: pointer;
            padding: 6px 8px;
            border-radius: 8px;
            color: var(--text-color);
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 13px;
        }
        
        .file-upload-btn:hover {
            background-color: var(--action-btn-hover);
        }
        
        .file-upload-btn svg {
            width: 18px;
            height: 18px;
            fill: currentColor;
        }
        
        /* 修改文件信息显示样式 */
        .file-info {
            display: none;
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 8px;
            padding: 8px 12px;
            margin-bottom: 10px;
            font-size: 14px;
            position: relative;
        }
        
        .file-info-name {
            font-weight: bold;
            margin-right: 10px;
        }
        
        .file-info-size {
            color: var(--action-btn-color);
            font-size: 12px;
        }
        
        .file-remove-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: transparent;
            border: none;
            cursor: pointer;
            color: var(--action-btn-color);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 4px;
            border-radius: 50%;
        }
        
        .file-remove-btn:hover {
            background-color: var(--action-btn-hover);
        }
        
        .file-remove-btn svg {
            width: 16px;
            height: 16px;
        }
        
        /* 导出按钮组样式 */
        .file-actions {
            position: absolute;
            left: 150px;
            bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .export-dropdown {
            position: relative;
        }
        
        .export-dropdown-btn {
            background: transparent;
            border: none;
            cursor: pointer;
            padding: 6px 8px;
            border-radius: 8px;
            color: var(--text-color);
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 13px;
        }
        
        .export-dropdown-btn:hover {
            background-color: var(--action-btn-hover);
        }
        
        .export-dropdown-btn svg {
            width: 18px;
            height: 18px;
            fill: currentColor;
        }
        
        .export-dropdown-content {
            display: none;
            position: absolute;
            bottom: 100%;
            left: 0;
            background: var(--card-bg);
            min-width: 150px;
            border: 1px solid var(--card-border);
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 1003; /* 提高z-index值 */
            margin-bottom: 8px;
        }
        
        .export-dropdown-content button {
            width: 100%;
            text-align: left;
            border-radius: 0;
            border: none;
            padding: 10px 15px;
        }
        
        .export-dropdown-content button:hover {
            background-color: var(--action-btn-hover);
        }
        
        .export-dropdown-content button:first-child {
            border-radius: 8px 8px 0 0;
        }
        
        .export-dropdown-content button:last-child {
            border-radius: 0 0 8px 8px;
        }

        /* 修改文件操作区域样式，保持在同一行 */
        .file-actions-container {
            display: flex;
            width: 100%;
            margin-top: 12px;
            gap: 10px;
            padding-top: 8px;
            border-top: 1px solid var(--card-border);
            justify-content: space-between;
        }
        
        .file-actions-group {
            display: flex;
            gap: 10px;
        }
        
        /* 修复导出下拉菜单显示问题 */
        .export-dropdown-content {
            display: none;
            position: absolute;
            bottom: 100%;
            left: 0;
            background: var(--card-bg);
            min-width: 150px;
            border: 1px solid var(--card-border);
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 1003; /* 提高z-index值 */
            margin-bottom: 8px;
        }
        
        /* 确保下拉菜单中的按钮样式正确 */
        .export-dropdown-content .file-button {
            width: 100%;
            text-align: left;
            border-radius: 0;
            border: none;
            padding: 10px 15px;
        }
        
        .export-dropdown-content .file-button:first-child {
            border-radius: 8px 8px 0 0;
        }
        
        .export-dropdown-content .file-button:last-child {
            border-radius: 0 0 8px 8px;
        }
        
        /* 修复文件按钮组的显示 */
        .file-button {
            display: flex;
            align-items: center;
            gap: 6px;
            background-color: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 6px;
            padding: 6px 10px;
            color: var(--text-color);
            font-size: 13px;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
        }
        
        .file-button svg {
            width: 16px;
            height: 16px;
            fill: currentColor;
            flex-shrink: 0;
        }
        
        /* 确保下拉菜单内容正确显示 */
        .export-dropdown-content {
            display: none;
            position: absolute;
            bottom: 100%;
            left: 0;
            background: var(--card-bg);
            min-width: 150px;
            border: 1px solid var(--card-border);
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 1003;
            margin-bottom: 8px;
        }
        
        /* 文件预览悬停样式 */
        .file-preview {
            position: absolute;
            top: 100%;
            left: 0;
            width: 400px;
            max-height: 300px;
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 1002;
            overflow-y: auto;
            display: none;
            white-space: pre-wrap;
            font-size: 13px;
            color: var(--text-color);
            margin-top: 8px;
        }

        /* 添加历史记录弹窗样式 */
        .history-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1100;
            align-items: center;
            justify-content: center;
        }
        
        .history-modal-content {
            background-color: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.2);
            width: 500px;
            max-width: 90%;
            max-height: 80vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            border: 1px solid var(--card-border);
        }
        
        .history-modal-header {
            padding: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--card-border);
        }
        
        .history-modal-header h3 {
            margin: 0;
            color: var(--text-color);
            font-size: 18px;
        }
        
        .close-modal {
            background: transparent;
            border: none;
            font-size: 24px;
            color: var(--text-color);
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        
        .close-modal:hover {
            background-color: var(--action-btn-hover);
        }
        
        .history-modal-body {
            padding: 16px;
            overflow-y: auto;
            max-height: calc(80vh - 60px);
        }
        
        .history-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .history-item {
            padding: 12px;
            border-radius: 8px;
            border: 1px solid var(--card-border);
            cursor: pointer;
            transition: all 0.2s ease;
            position: relative;
            background-color: var(--card-bg);
        }
        
        .history-item:hover {
            background-color: var(--keyword-active-bg);
        }
        
        .history-item.active {
            border-color: var(--keyword-active-color);
            background-color: var(--keyword-active-bg);
        }
        
        .history-title {
            font-weight: bold;
            color: var(--text-color);
            margin-bottom: 8px;
            padding-right: 30px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .history-date {
            font-size: 12px;
            color: var(--action-btn-color);
        }
        
        .history-delete-btn {
            position: absolute;
            right: 10px;
            top: 10px;
            background: transparent;
            border: none;
            width: 24px;
            height: 24px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border-radius: 50%;
            color: var(--action-btn-color);
        }
        
        .history-delete-btn:hover {
            background-color: rgba(255,0,0,0.1);
            color: #ff4d4d;
        }
        
        .history-delete-btn svg {
            width: 16px;
            height: 16px;
        }
        
        .empty-history {
            text-align: center;
            padding: 20px;
            color: var(--action-btn-color);
        }

        /* 历史记录在导航栏下方显示方式 */
        .history-items {
            padding: 0 10px;
            margin-top: 20px;
            max-height: calc(100vh - 250px);
            overflow-y: auto;
        }

        .history-item {
            padding: 10px;
            border-radius: 8px;
            border: 1px solid var(--card-border);
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            background-color: var(--card-bg);
        }

        .history-item:hover {
            background-color: var(--keyword-active-bg);
        }

        .history-item.active {
            border-color: var(--keyword-active-color);
            background-color: var(--keyword-active-bg);
        }

        .history-title {
            font-weight: bold;
            color: var(--text-color);
            margin-bottom: 5px;
            font-size: 13px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .history-date {
            font-size: 11px;
            color: var(--action-btn-color);
        }

        /* 历史记录标题 */
        .history-section-title {
            padding: 8px 15px;
            font-size: 13px;
            font-weight: bold;
            color: var(--text-color);
            opacity: 0.8;
            border-bottom: 1px solid var(--card-border);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .history-section-title svg {
            flex-shrink: 0;
            opacity: 0.8;
        }
        
        .history-section-title span {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .sidebar:not(:hover) .history-section-title {
            height: 30px;
            box-sizing: border-box;
            border-bottom: none;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .sidebar:not(:hover) .history-section-title svg {
            margin-right: 0;
        }
        
        .sidebar:not(:hover) .history-section-title span {
            display: none;
        }
        
        .sidebar:not(:hover) .history-section-title::after {
            content: '\2022'; /* 添加圆点提示有历史记录 */
            display: inline-block;
            margin-left: 2px;
            font-size: 16px;
            color: var(--btn-primary);
        }
        
        .empty-history {
            text-align: center;
            padding: 20px;
            color: var(--action-btn-color);
            font-size: 13px;
        }

        /* 优化导航栏中历史记录列表样式 */
        .history-section {
            margin-top: 20px;
            width: 100%;
            overflow: hidden;
        }
        
        .history-section-title {
            padding: 8px 15px;
            font-size: 13px;
            font-weight: bold;
            color: var(--text-color);
            opacity: 0.8;
            border-bottom: 1px solid var(--card-border);
        }

        .history-items {
            max-height: calc(100vh - 250px);
            overflow-y: auto;
            padding: 5px 10px;
        }

        .sidebar:hover .history-items {
            padding: 5px 15px;
        }

        .history-item {
            padding: 8px 10px;
            border-radius: 6px;
            margin-bottom: 5px;
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
            border-left: 2px solid transparent;
        }

        .history-item:hover {
            background-color: var(--keyword-active-bg);
            border-left-color: var(--keyword-active-color);
        }

        .history-item.active {
            background-color: var(--keyword-active-bg);
            border-left-color: var(--btn-primary);
        }

        .history-title {
            font-size: 12px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            color: var(--text-color);
            margin-right: 20px;
        }

        .history-date {
            font-size: 10px;
            color: var(--action-btn-color);
            margin-top: 3px;
        }

        .history-delete-btn {
            position: absolute;
            right: 5px;
            top: 50%;
            transform: translateY(-50%);
            background: transparent;
            border: none;
            width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0;
            opacity: 0.6;
            color: var(--action-btn-color);
            cursor: pointer;
            border-radius: 50%;
        }

        .history-delete-btn:hover {
            opacity: 1;
            background-color: rgba(255,0,0,0.1);
            color: #ff4d4d;
        }

        .history-delete-btn svg {
            width: 14px;
            height: 14px;
        }

        .empty-history {
            padding: 15px 10px;
            text-align: center;
            color: var(--action-btn-color);
            font-size: 11px;
            opacity: 0.7;
        }

        /* 为侧边栏滚动条添加样式 */
        .history-items::-webkit-scrollbar {
            width: 4px;
        }

        .history-items::-webkit-scrollbar-track {
            background: transparent;
        }

        .history-items::-webkit-scrollbar-thumb {
            background-color: var(--card-border);
            border-radius: 4px;
        }

        .history-items::-webkit-scrollbar-thumb:hover {
            background-color: var(--keyword-active-color);
        }

        /* 添加历史记录侧边栏样式 */
        .history-section {
            width: 100%;
            margin-top: 15px;
        }

        .sidebar .history-section-title {
            font-size: 12px;
            padding: 8px 10px;
            white-space: nowrap;
            overflow: hidden;
            opacity: 0;
            transition: opacity 0.3s ease;
            text-align: center;
        }

        .sidebar:hover .history-section-title {
            opacity: 1;
            padding: 8px 15px;
            text-align: left;
        }

        .sidebar .history-item {
            border-left: none;
            border-radius: 0;
            margin: 0;
            padding: 10px;
            text-align: center;
        }

        .sidebar:hover .history-item {
            text-align: left;
            border-left: 2px solid transparent;
            border-radius: 6px;
            margin: 0 0 5px 0;
        }
        
        .sidebar .history-title {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .sidebar:hover .history-title {
            opacity: 1;
        }
        
        .sidebar .history-date {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .sidebar:hover .history-date {
            opacity: 1;
        }
        
        .sidebar .history-delete-btn {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .sidebar:hover .history-delete-btn {
            opacity: 0.6;
        }
        
        .sidebar .history-delete-btn:hover {
            opacity: 1;
        }
        
        .sidebar .empty-history {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .sidebar:hover .empty-history {
            opacity: 0.7;
        }
        
        /* 侧边栏收起时历史记录项的圆点标记 */
        .sidebar .history-item::before {
            content: '';
            display: block;
            width: 6px;
            height: 6px;
            background-color: var(--action-btn-color);
            border-radius: 50%;
            margin: 0 auto;
        }
        
        .sidebar .history-item.active::before {
            background-color: var(--btn-primary);
        }
        
        .sidebar:hover .history-item::before {
            display: none;
        }

        /* 优化历史记录区域在导航栏收起时的显示 */
        .sidebar .history-section {
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        .sidebar:not(:hover) .history-section-title {
            height: 30px;
            box-sizing: border-box;
            border-bottom: none;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .sidebar:not(:hover) .history-section-title::after {
            content: attr(data-count); /* 使用自定义属性显示历史记录数量 */
            display: inline-block;
            margin-left: 5px;
            font-size: 10px;
            color: var(--btn-primary);
            background-color: var(--keyword-active-bg);
            border-radius: 50%;
            width: 16px;
            height: 16px;
            line-height: 16px;
            text-align: center;
        }
        
        .sidebar:not(:hover) .history-section-title[data-count="0"]::after {
            display: none; /* 如果没有历史记录，不显示圆点 */
        }
        
        .sidebar:not(:hover) .history-items {
            display: none;
        }
        
        /* 修改历史项目在边栏展开时的样式 */
        .sidebar:hover .history-item {
            display: flex;
            flex-direction: column;
            padding: 8px 12px;
            border-radius: 6px;
            background-color: var(--card-bg);
            border-left: 2px solid transparent;
            margin-bottom: 6px;
            transition: all 0.2s;
        }
        
        .sidebar:hover .history-item:hover {
            background-color: var(--keyword-active-bg);
            border-left-color: var(--keyword-active-color);
        }
        
        .sidebar:hover .history-item.active {
            background-color: var(--keyword-active-bg);
            border-left-color: var(--btn-primary);
        }
        
        /* 删除按钮样式优化 */
        .history-delete-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: transparent;
            border: none;
            padding: 0;
            cursor: pointer;
            border-radius: 50%;
            opacity: 0.5;
            transition: all 0.2s;
        }
        
        .history-delete-btn:hover {
            opacity: 1;
            background-color: rgba(255,0,0,0.1);
            color: #ff4d4d;
        }
        
        .history-delete-btn svg {
            width: 16px;
            height: 16px;
        }

        /* 输入区域基本样式 */
        .input-area {
            position: fixed;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 98%; /* 与聊天容器宽度匹配 */
            max-width: 800px;
            background: transparent;
            padding: 20px;
            z-index: 1000;
            transition: all 0.5s ease-in-out;
            top: 50%;
        }
        
        /* 优化树节点悬停提示框 */
        .tree-tooltip {
            position: fixed;
            max-width: 280px; /* 限制最大宽度，确保不会超出右侧区域 */
            padding: 15px;
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            z-index: 1010;
            display: none;
            pointer-events: none;
            font-size: 14px;
            color: var(--text-color);
            line-height: 1.5;
            overflow-y: visible;
            max-height: none;
            word-break: break-word;
            transform-origin: left top;
            transform: scale(1);
            transition: transform 0.2s ease;
        }

        /* 添加消息分割线样式 */
        .message-divider {
            display: flex;
            align-items: center;
            text-align: center;
            margin: 20px 0;
            color: var(--text-color);
            opacity: 0.7;
        }
        
        /* 添加被禁用消息的样式 */
        .disabled-message {
            opacity: 0.7;
            position: relative;
        }
        
        .disabled-message::after {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--bg-color);
            opacity: 0.2;
            pointer-events: none;
        }
        
        .disabled-message .message-content del,
        .disabled-message .message-content span[style*="color: blue"],
        .disabled-message .message-content span[style*="background-color"] {
            cursor: default !important;
            text-decoration: none;
        }
        
        /* 消息分割线边框样式 */
        .message-divider::before,
        .message-divider::after {
            content: "";
            flex: 1;
            border-bottom: 1px solid var(--card-border);
        }
        
        .message-divider span {
            margin: 0 10px;
            padding: 3px 8px;
            background-color: var(--card-bg);
            border-radius: 10px;
            font-size: 0.8em;
            box-shadow: 0 1px 2px var(--card-shadow);
        }

        /* 导出按钮样式 */
        .export-button {
            margin-left: 10px;
        }

        /* 模态窗口样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            overflow: auto;
        }

        .modal-content {
            background-color: var(--card-bg);
            margin: 5% auto;
            padding: 0;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            width: 80%;
            max-width: 700px;
            max-height: 80vh;
            overflow: hidden;
            animation: modalFadeIn 0.3s;
        }

        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid var(--card-border);
        }

        .modal-header h3 {
            margin: 0;
            font-size: 18px;
            color: var(--text-color);
        }

        .close-modal {
            color: var(--text-color);
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: color 0.2s;
        }

        .close-modal:hover {
            color: var(--btn-primary);
        }

        .modal-body {
            padding: 20px;
            max-height: calc(80vh - 60px);
            overflow-y: auto;
            overflow-x: hidden; /* 禁止横向滚动 */
        }

        /* 导出选项样式 */
        .export-options {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
        }

        .export-format {
            flex: 2;
            min-width: 250px;
        }

        .export-filename {
            flex: 1;
            min-width: 200px;
        }

        .export-format p, .export-filename p {
            margin-top: 0;
            margin-bottom: 10px;
            font-weight: bold;
        }

        .export-filename input {
            width: 100%;
            max-width: 200px; /* 限制输入框宽度 */
            padding: 10px;
            border: 1px solid var(--card-border);
            border-radius: 5px;
            background-color: var(--input-bg);
            color: var(--text-color);
        }

        /* 导出预览样式 */
        .export-preview {
            margin-bottom: 20px;
        }

        .export-preview p {
            margin-top: 0;
            margin-bottom: 10px;
            font-weight: bold;
        }

        .preview-content {
            padding: 15px;
            border: 1px solid var(--card-border);
            border-radius: 5px;
            max-height: 200px;
            overflow-y: auto;
            background-color: var(--bg-color);
            color: var(--text-color);
        }

        /* 导出按钮样式 */
        .export-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.2s;
        }

        .btn-primary {
            background-color: var(--btn-primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: var(--btn-hover);
        }

        .btn-secondary {
            background-color: var(--card-border);
            color: var(--text-color);
        }

        .btn-secondary:hover {
            background-color: #d0d0d0;
        }

        .format-options {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }

        .format-option {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px;
            border: 2px solid var(--card-border);
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            width: 80px;
        }

        .format-option:hover {
            border-color: var(--btn-primary);
            background-color: var(--hover-bg);
        }

        .format-option input {
            position: absolute;
            opacity: 0;
        }

        .format-option input:checked + .format-icon + .format-name,
        .format-option input:checked + .format-icon {
            color: var(--btn-primary);
        }

        .format-option input:checked ~ * {
            font-weight: bold;
        }

        .format-option input:checked + .format-icon svg {
            fill: var(--btn-primary);
        }

        .format-icon {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 8px;
        }

        .format-name {
            font-size: 12px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="sidebar" id="sidebar">
            <div class="nav-header">
                <div class="logo">
                    <div class="logo-icon">润</div>
                    <div class="logo-text">润色智能体</div>
                </div>
                <div class="mobile-menu-toggle" id="mobileMenuToggle">
                    <svg viewBox="0 0 24 24" fill="currentColor">
                        <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
                    </svg>
                </div>
            </div>
            
            <!-- 主要功能按钮 -->
            <div class="nav-items">
                <a href="#" class="nav-item" id="newChatBtn">
                    <div class="nav-icon">
                        <svg viewBox="0 0 24 24" fill="currentColor">
                            <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
                        </svg>
                    </div>
                    <div class="nav-text">新建会话</div>
                </a>
                <!-- 删除历史记录按钮 -->
                
                <!-- 历史记录列表 -->
                <div class="history-section">
                    <div class="history-section-title">
                        <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16">
                            <path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/>
                        </svg>
                        <span>历史记录</span>
                    </div>
                    <div class="history-items" id="historyItems">
                        <!-- 历史记录将在这里动态添加 -->
                    </div>
                </div>
            </div>

            <!-- 底部按钮组 -->
            <div class="nav-bottom">
                <a href="#" class="nav-item" id="legendToggle">
                    <div class="nav-icon">
                        <svg viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/>
                        </svg>
                    </div>
                    <div class="nav-text">修改说明</div>
                    <div class="legend-tooltip">
                        <div class="legend-title">修改说明</div>
                        <div class="legend-item">
                            <span class="legend-sample legend-delete">删除</span>
                            <span>完全删除的内容</span>
                        </div>
                        <div class="legend-item">
                            <span class="legend-sample legend-add">新增</span>
                            <span>完全新增的内容</span>
                        </div>
                        <div class="legend-item">
                            <span class="legend-sample legend-modify">改写</span>
                            <span>在原有内容基础上改动</span>
                        </div>
                    </div>
                </a>
                <a href="#" class="nav-item theme-toggle-nav" id="themeToggle">
                    <div class="nav-icon">
                        <svg id="lightIcon" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zM2 13h2c.55 0 1-.45 1-1s-.45-1-1-1H2c-.55 0-1 .45-1 1s.45 1 1 1zm18 0h2c.55 0 1-.45 1-1s-.45-1-1-1h-2c-.55 0-1 .45-1 1s.45 1 1 1zM11 2v2c0 .55.45 1 1 1s1-.45 1-1V2c0-.55-.45-1-1-1s-1 .45-1 1zm0 18v2c0 .55.45 1 1 1s1-.45 1-1v-2c0-.55-.45-1-1-1s-1 .45-1 1zM5.99 4.58c-.39-.39-1.03-.39-1.41 0-.39.39-.39 1.03 0 1.41l1.06 1.06c.39.39 1.03.39 1.41 0 .39-.39.39-1.03 0-1.41L5.99 4.58zm12.37 12.37c-.39-.39-1.03-.39-1.41 0-.39.39-.39 1.03 0 1.41l1.06 1.06c.39.39 1.03.39 1.41 0 .39-.39.39-1.03 0-1.41l-1.06-1.06zm1.06-10.96c.39-.39.39-1.03 0-1.41-.39-.39-1.03-.39-1.41 0l-1.06 1.06c-.39.39-.39 1.03 0 1.41.39.39 1.03.39 1.41 0l1.06-1.06zM7.05 18.36c.39-.39.39-1.03 0-1.41-.39-.39-1.03-.39-1.41 0l-1.06 1.06c-.39.39-.39 1.03 0 1.41.39.39 1.03.39 1.41 0l1.06-1.06z"/>
                        </svg>
                        <svg id="darkIcon" viewBox="0 0 24 24" fill="currentColor" style="display: none;">
                            <path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9c0-.46-.04-.92-.1-1.36-.98 1.37-2.58 2.26-4.4 2.26-2.98 0-5.4-2.42-5.4-5.4 0-1.81.89-3.42 2.26-4.4-.44-.06-.9-.1-1.36-.1z"/>
                        </svg>
                    </div>
                    <div class="nav-text">切换主题</div>
                </a>
            </div>
        </div>

        <div class="mobile-menu-toggle" id="mobileMenuToggle" style="display: none;">
            <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
                <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
            </svg>
        </div>

        <div class="main-content">
            <div class="chat-container">
                <div class="chat-messages" id="chatMessages">
                    <!-- 消息将在这里动态添加 -->
                </div>
            </div>
            <!-- 添加树结构容器 -->
            <div class="tree-container" id="treeContainer">
                <!-- 树节点将在这里动态添加 -->
            </div>
            <div class="input-area">
                <div class="input-container">
                    <!-- 添加文件信息显示 -->
                    <div class="file-info" id="fileInfo">
                        <span class="file-info-name" id="fileName"></span>
                        <div class="file-preview" id="filePreview"></div>
                        <button class="file-remove-btn" id="removeFile">
                            <svg viewBox="0 0 24 24" fill="currentColor">
                                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                            </svg>
                        </button>
                    </div>
                    
                    <textarea id="input" placeholder="请输入需要润色的文本..." rows="1" oninput="this.style.height = ''; this.style.height = this.scrollHeight + 'px'"></textarea>
                    
                    <button id="submit">发送</button>
                    
                    <div class="style-buttons">
                        <button class="keyword-btn" data-type="emotional">情感的</button>
                        <button class="keyword-btn" data-type="rigorous">严谨的</button>
                        <button class="keyword-btn" data-type="expand">扩写</button>
                        <button class="keyword-btn" data-type="compress">缩写</button>
                        <button class="keyword-btn" data-type="elegant">优雅的</button>
                        <button class="keyword-btn" data-type="simple">简洁的</button>
                    </div>
                    
                    <!-- 文体和领域选择 -->
                    <div class="domain-selector">
                        <div class="selector-group">
                            <label class="style-label" for="style-select">文体类型:</label>
                            <select class="style-dropdown" id="style-select">
                                <option value="">通用文体</option>
                                <option value="academic">学术论文</option>
                                <option value="narrative">叙事文学</option>
                                <option value="formal">正式文件</option>
                                <option value="creative">创意写作</option>
                                <option value="news">新闻报道</option>
                                <option value="technical">技术文档</option>
                                <option value="speech">演讲稿</option>
                                <option value="blog">博客文章</option>
                            </select>
                        </div>
                        
                        <div class="selector-group">
                            <label class="domain-label" for="domain-select">专业领域:</label>
                            <select class="domain-dropdown" id="domain-select">
                                <option value="">通用领域</option>
                                <option value="medical">医学</option>
                                <option value="legal">法律</option>
                                <option value="tech">技术</option>
                                <option value="academic">学术</option>
                                <option value="business">商业</option>
                                <option value="science">科学</option>
                                <option value="engineering">工程</option>
                                <option value="education">教育</option>
                                <option value="art">艺术</option>
                                <option value="finance">金融</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- 文件操作放在最后一行 -->
                    <div class="file-actions-container">
                        <div class="file-actions-group">
                            <label for="file-input" class="file-button">
                                <svg viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/>
                                </svg>
                                上传文件
                            </label>
                            <input type="file" id="file-input" accept=".txt,.doc,.docx,.pdf" style="display:none;">
                            
                            <div class="export-dropdown" id="exportDropdown">
                                <button class="file-button" id="exportBtn">
                                    <svg viewBox="0 0 24 24" fill="currentColor">
                                        <path d="M19 12v7H5v-7H3v7c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zm-6 .67l2.59-2.58L17 11.5l-5 5-5-5 1.41-1.41L11 12.67V3h2v9.67z"/>
                                    </svg>
                                    导出文件
                                </button>
                                <div class="export-dropdown-content" id="exportOptions">
                                    <button class="file-button" id="exportDocx">
                                        <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16">
                                            <path d="M6 2h8l6 6v12c0 1.1-.9 2-2 2H6c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2zm0 2v16h12V8h-6V4H6zm7 1l4 4h-4V5zm-1 4h1v4h-1v-4zm-2 0h1v4h-1v-4z"/>
                                        </svg>
                                        导出为DOCX
                                    </button>
                                    <button class="file-button" id="exportPdf">
                                        <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16">
                                            <path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v1.25c0 .41-.34.75-.75.75s-.75-.34-.75-.75V8c0-.55.45-1 1-1H10c.83 0 1.5.67 1.5 1.5v1zm5 2c0 .83-.67 1.5-1.5 1.5h-2c-.28 0-.5-.22-.5-.5v-5c0-.28.22-.5.5-.5h2c.83 0 1.5.67 1.5 1.5v3zm4-3.75c0 .41-.34.75-.75.75H19v1h.75c.41 0 .75.34.75.75s-.34.75-.75.75H19v1.25c0 .41-.34.75-.75.75s-.75-.34-.75-.75V8c0-.55.45-1 1-1h1.25c.41 0 .75.34.75.75zM9 9.5h1v-1H9v1zM3 6c-.55 0-1 .45-1 1v13c0 1.1.9 2 2 2h13c.55 0 1-.45 1-1s-.45-1-1-1H5c-.55 0-1-.45-1-1V7c0-.55-.45-1-1-1zm11 5.5h1v-3h-1v3z"/>
                                        </svg>
                                        导出为PDF
                                    </button>
                                    <button class="file-button" id="exportTxt">
                                        <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16">
                                            <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zM6 20V4h7v5h5v11H6zM8 15h8v2H8v-2zm0-4h8v2H8v-2z"/>
                                        </svg>
                                        导出为TXT
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 在 .main-content 内添加文字思维导图容器 -->
            <div class="text-tree-container">
                <div class="text-tree-title">对话思维导图</div>
                <div id="textTree" class="text-tree"></div>
            </div>
        </div>

        <div class="legend">
            <div class="legend-title">修改说明</div>
            <div class="legend-item">
                <span class="legend-sample legend-delete">删除</span>
                <span>完全删除的内容</span>
            </div>
            <div class="legend-item">
                <span class="legend-sample legend-add">新增</span>
                <span>完全新增的内容</span>
            </div>
            <div class="legend-item">
                <span class="legend-sample legend-modify">改写</span>
                <span>在原有内容基础上改动</span>
            </div>
        </div>

        <!-- 添加历史记录弹窗容器 -->
        <div class="history-modal" id="historyModal">
            <div class="history-modal-content">
                <div class="history-modal-header">
                    <h3>历史会话</h3>
                    <button class="close-modal" id="closeHistoryModal">×</button>
                </div>
                <div class="history-modal-body">
                    <div class="history-list" id="historyList">
                        <!-- 历史会话列表将在这里动态添加 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 导出文件模态窗口 -->
    <div id="exportModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>导出文件</h3>
                <span class="close-modal" id="closeExportModal">&times;</span>
            </div>
            <div class="modal-body">
                <div class="export-options">
                    <div class="export-format">
                        <p>选择文件格式：</p>
                        <div class="format-options">
                            <label class="format-option">
                                <input type="radio" name="format" value="txt" checked>
                                <span class="format-icon">
                                    <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
                                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zM14 8V3.5L18.5 8H14zm2 11H8v-2h8v2zm0-4H8v-2h8v2z"/>
                                    </svg>
                                </span>
                                <span class="format-name">TXT文本</span>
                            </label>
                            <label class="format-option">
                                <input type="radio" name="format" value="docx">
                                <span class="format-icon">
                                    <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
                                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6zM14 8V3.5L18.5 8H14zm2 11H8v-2h8v2zm0-4H8v-2h8v2z"/>
                                    </svg>
                                </span>
                                <span class="format-name">Word文档</span>
                            </label>
                            <label class="format-option">
                                <input type="radio" name="format" value="pdf">
                                <span class="format-icon">
                                    <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
                                        <path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v1.25c0 .41-.34.75-.75.75s-.75-.34-.75-.75V8c0-.55.45-1 1-1H10c.83 0 1.5.67 1.5 1.5v1zm5 2c0 .83-.67 1.5-1.5 1.5h-2c-.28 0-.5-.22-.5-.5v-5c0-.28.22-.5.5-.5h2c.83 0 1.5.67 1.5 1.5v3zm4-3.75c0 .41-.34.75-.75.75H19v1h.75c.41 0 .75.34.75.75s-.34.75-.75.75H19v1.25c0 .41-.34.75-.75.75s-.75-.34-.75-.75V8c0-.55.45-1 1-1h1.25c.41 0 .75.34.75.75zM9 9.5h1v-1H9v1zM3 6c-.55 0-1 .45-1 1v13c0 1.1.9 2 2 2h13c.55 0 1-.45 1-1s-.45-1-1-1H5c-.55 0-1-.45-1-1V7c0-.55-.45-1-1-1zm11 5.5h1v-3h-1v3z"/>
                                    </svg>
                                </span>
                                <span class="format-name">PDF文档</span>
                            </label>
                        </div>
                    </div>
                    <div class="export-filename">
                        <p>文件名：</p>
                        <input type="text" id="exportFilename" placeholder="输入文件名（不含扩展名）" value="润色结果">
                    </div>
                </div>
                <div class="export-preview">
                    <p>内容预览：</p>
                    <div id="exportPreview" class="preview-content"></div>
                </div>
                <div class="export-buttons">
                    <button id="cancelExport" class="btn btn-secondary">取消</button>
                    <button id="confirmExport" class="btn btn-primary">确认导出</button>
                </div>
            </div>
        </div>

    <script>
        let isFirstMessage = true;
        let messageCounter = 0; // 用于跟踪聊天框中的消息数量
        let currentSessionId = null; // 用于跟踪当前会话ID

        class MessageTree {
            constructor(containerId) {
                this.container = document.getElementById(containerId);
                this.nodes = [];
                this.rootId = null;
                this.levelCounters = {};
                this.currentLevel = 0;
                
                // 创建提示框
                if (!document.getElementById('tree-tooltip')) {
                    const tooltip = document.createElement('div');
                    tooltip.id = 'tree-tooltip';
                    tooltip.className = 'tree-tooltip';
                    document.body.appendChild(tooltip);
                }
                
                this.initD3Tree();
            }

            initD3Tree() {
                // 清空容器
                d3.select(this.container).selectAll("*").remove();
                
                // 添加标题
                d3.select(this.container)
                    .append("div")
                    .attr("class", "tree-title")
                    .text("消息对话树");
                
                const width = this.container.clientWidth - 40;
                const height = this.container.clientHeight - 100;
                
                // 创建SVG并添加缩放功能
                this.svg = d3.select(this.container)
                    .append("svg")
                    .attr("width", width)
                    .attr("height", height)
                    .attr("viewBox", [0, 0, width, height])
                    .attr("preserveAspectRatio", "xMidYMid meet")
                    .call(d3.zoom()
                        .scaleExtent([0.5, 2])
                        .on("zoom", (event) => {
                            this.root.attr("transform", event.transform);
                        }));
                
                // 创建根容器g元素
                this.root = this.svg.append("g");
            }

            // 添加完全重置树的方法
            resetTree() {
                // 保存当前状态以便恢复
                const oldTreeState = window.treeNodeState || {};
                
                this.nodes = []; // 清空所有节点
                this.rootId = null;
                this.levelCounters = {};
                this.currentLevel = 0;
                
                // 创建新的根节点
                const rootNode = {
                    id: "0",
                    content: "根节点",
                    parentId: null,
                    isUser: false,
                    isRoot: true
                };
                
                this.nodes.push(rootNode);
                this.rootId = "0";
                
                // 重置树状态但保留根节点状态
                window.treeNodeState = {};
                if (oldTreeState["0"]) {
                    window.treeNodeState["0"] = oldTreeState["0"];
                }
                
                // 重新初始化树
                this.initD3Tree();
                this.render();
            }

            addNode(content, parentId = null, isRetry = false, isUser = false, isPartial = false, isNewInput = false) {
                let nodeId;
                
                // 处理根节点
                if (isNewInput && isUser) {
                    nodeId = "0";
                    this.nodes = []; // 清空现有节点
                    this.rootId = nodeId;
                    this.levelCounters = {};
                    this.currentLevel = 1;
                }
                // 处理用户的特殊消息（再试一次/重新润色）
                else if (isUser && (content.startsWith("再试一次润色：") || content.startsWith("重新润色指定区域："))) {
                    nodeId = parentId;
                    return nodeId; // 直接返回父节点ID，不创建新节点
                }
                // 处理普通消息
                else {
                    const parentNode = this.nodes.find(n => n.id === parentId);
                    
                    if (!parentNode) {
                        // 如果找不到父节点，作为根节点的子节点
                        const rootLevel = 1;
                        if (!this.levelCounters[rootLevel]) {
                            this.levelCounters[rootLevel] = 0;
                        }
                        this.levelCounters[rootLevel]++;
                        nodeId = `${rootLevel}-${this.levelCounters[rootLevel]}`;
                    } else {
                        // 找到父节点，创建其子节点
                        const parentLevel = parseInt(parentNode.id.split('-')[0]) || 0;
                        const currentLevel = parentLevel + 1;
                        
                        if (!this.levelCounters[currentLevel]) {
                            this.levelCounters[currentLevel] = 0;
                        }
                        this.levelCounters[currentLevel]++;
                        
                        nodeId = `${currentLevel}-${this.levelCounters[currentLevel]}`;
                    }
                }
                
                // 创建新节点
                const newNode = {
                    id: nodeId,
                    content: content,
                    parentId: parentId || (nodeId === "0" ? null : "0"),
                    isUser: isUser,
                    isRoot: nodeId === "0"
                };
                
                // 添加节点到数组
                this.nodes.push(newNode);
                
                // 渲染树
                this.render();
                
                return nodeId;
            }

            render() {
                if (!this.container || this.nodes.length === 0) return;
                
                // 清空容器
                this.root.selectAll("*").remove();
                
                const width = this.container.clientWidth - 40;
                const height = this.container.clientHeight - 100;
                
                try {
                    // 创建层次结构
                    const hierarchy = d3.stratify()
                        .id(d => d.id)
                        .parentId(d => d.parentId)
                        (this.nodes);
                    
                    // 调整树布局大小和间距
                    const treeLayout = d3.tree()
                        .size([width * 0.9, height * 0.9])  // 增加利用空间
                        .nodeSize([40, 60])  // 设置固定的节点大小
                        .separation((a, b) => (a.parent === b.parent ? 1.5 : 2));
                    
                    const rootNode = treeLayout(hierarchy);
                    
                    // 计算布局边界
                    let minX = Infinity, maxX = -Infinity;
                    rootNode.descendants().forEach(d => {
                        minX = Math.min(minX, d.x);
                        maxX = Math.max(maxX, d.x);
                    });
                    
                    // 调整整体位置以居中显示
                    const centerX = (maxX + minX) / 2;
                    this.root.attr("transform", `translate(${width/2 - centerX}, 50)`);
                    
                    // 绘制连接线，使用曲线
                    this.root.selectAll(".link")
                        .data(rootNode.links())
                        .enter()
                        .append("path")
                        .attr("class", "link")
                        .attr("d", d3.linkVertical()
                            .x(d => d.x)
                            .y(d => d.y))
                        .attr("stroke", "var(--card-border)")
                        .attr("stroke-width", 1.5)
                        .attr("fill", "none");
                    
                    // 创建节点组
                    const nodes = this.root.selectAll(".node")
                        .data(rootNode.descendants())
                        .enter()
                        .append("g")
                        .attr("class", d => {
                            let classes = "node";
                            if (d.data.isRoot) classes += " root-node";
                            if (d.data.isUser) classes += " user-node";
                            if (d.data.id === this.activeNodeId) classes += " active";
                            return classes;
                        })
                        .attr("transform", d => `translate(${d.x},${d.y})`);
                    
                    // 添加节点圆圈
                    nodes.append("circle")
                        .attr("r", d => d.data.isRoot ? 15 : 8)
                        .attr("fill", d => {
                            if (d.data.isRoot) return "var(--btn-primary)";
                            if (d.data.isUser) return "var(--user-msg-bg)";
                            return "var(--card-bg)";
                        })
                        .attr("stroke", d => d.data.isRoot ? "var(--btn-hover)" : "var(--keyword-active-color)")
                        .attr("stroke-width", 2);
                    
                    // 添加节点文本
                    nodes.append("text")
                        .attr("dy", -12)
                        .attr("text-anchor", "middle")
                        .attr("font-size", "12px")
                        .attr("fill", "var(--text-color)")
                        .text(d => d.data.id);
                    
                    // 添加交互
                    nodes
                        .on("mouseover", (event, d) => {
                            // 获取或创建提示框
                            let tooltip = document.getElementById('tree-tooltip');
                            if (!tooltip) {
                                tooltip = document.createElement('div');
                                tooltip.id = 'tree-tooltip';
                                tooltip.className = 'tree-tooltip';
                                document.body.appendChild(tooltip);
                            }
                            
                            // 设置内容并显示
                            const content = d.data.content.replace(/<[^>]*>/g, '');
                            tooltip.textContent = content;
                            tooltip.style.display = 'block';
                            
                            // 获取节点位置和右侧区域位置
                            const rect = event.currentTarget.getBoundingClientRect();
                            const treeContainer = document.getElementById('treeContainer');
                            const treeRect = treeContainer.getBoundingClientRect();
                            
                            // 计算提示框位置，确保在树容器内
                            let leftPos = rect.right + 15;
                            // 确保提示框不会超出右侧边界
                            const maxRight = treeRect.right - 20; // 右侧边界减去边距
                            // 检测提示框是否会超出右侧边界
                            if (leftPos + 280 > maxRight) { // 280px是提示框的最大宽度
                                // 如果会超出，则显示在左侧
                                leftPos = Math.max(treeRect.left + 10, rect.left - 290);
                            }
                            
                            tooltip.style.left = leftPos + 'px';
                            tooltip.style.top = Math.max(10, rect.top - 20) + 'px';
                            
                            // 添加动态效果
                            tooltip.style.transform = 'scale(0.95)';
                            setTimeout(() => {
                                tooltip.style.transform = 'scale(1)';
                            }, 50);
                            
                            // 高亮当前节点
                            d3.select(event.currentTarget)
                                .select("circle")
                                .transition()
                                .duration(200)
                                .attr("r", d => d.data.isRoot ? 17 : 10);
                        })
                        .on("mousemove", (event) => {
                            // 不做任何操作
                        })
                        .on("mouseout", (event) => {
                            const tooltip = document.getElementById('tree-tooltip');
                            if (tooltip) {
                                tooltip.style.display = 'none';
                            }
                            
                            // 恢复节点大小
                            d3.select(event.currentTarget)
                                .select("circle")
                                .transition()
                                .duration(200)
                                .attr("r", d => d.data.isRoot ? 15 : 8);
                        })
                        .on("click", (event, d) => {
                            // 隐藏提示框
                            const tooltip = document.getElementById('tree-tooltip');
                            if (tooltip) {
                                tooltip.style.display = 'none';
                            }
                            
                            this.activeNodeId = d.data.id;
                            this.scrollToMessage(d.data.id);
                            this.render(); // 重新渲染以更新活动状态
                        });
                    
                } catch (error) {
                    console.error("渲染树时出错:", error);
                }
            }

            scrollToMessage(nodeId) {
                // 查找目标消息元素
                const messageElement = document.querySelector(`[data-id="${nodeId}"]`);
                
                // 检查消息是否被禁用
                if (messageElement && messageElement.getAttribute('data-disabled') === 'true') {
                    console.log(`消息ID ${nodeId} 已被禁用，不可跳转`);
                    return; // 不执行跳转
                }
                
                if (messageElement) {
                    // 移除之前的活动状态
                    document.querySelectorAll('.message.active').forEach(el => {
                        el.classList.remove('active');
                    });
                    
                    // 添加活动状态
                    messageElement.classList.add('active');
                    
                    // 滚动到消息
                    messageElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    messageElement.classList.add('highlight');
                    setTimeout(() => messageElement.classList.remove('highlight'), 1000);
                    
                    // 高亮树节点
                    this.svg.selectAll(".node").classed("active", d => d.data.id === nodeId);
                }
            }

            // 添加一个方法来更新活动节点
            setActiveNode(nodeId) {
                this.activeNodeId = nodeId;
                this.render();
            }
        }

        // 初始化并修改树切换按钮逻辑
        const messageTree = new MessageTree('treeContainer');

        // 移除树切换按钮的事件处理
        // document.getElementById('toggleTreeBtn').addEventListener('click', function() {
        //     const treeContainer = document.getElementById('treeContainer');
        //     const mainContent = document.querySelector('.main-content');
            
        //     if (treeContainer.style.display === 'none' || !treeContainer.style.display) {
        //         console.log("显示树容器");
        //         treeContainer.style.display = 'flex';
        //         mainContent.classList.add('tree-visible');
                
        //         // 确保在显示前重新初始化和渲染
        //         setTimeout(() => {
        //             messageTree.initD3Tree();
        //             messageTree.render();
        //         }, 50);
        //     } else {
        //         console.log("隐藏树容器");
        //         treeContainer.style.display = 'none';
        //         mainContent.classList.remove('tree-visible');
        //     }
        // });

        // 移除初始隐藏树容器的代码
        // document.getElementById('treeContainer').style.display = 'none';

        async function addMessage(text, isUser = false, parentId = null, isRetry = false, isPartial = false, isNewInput = false) {
            if (isFirstMessage) {
                document.querySelector('.input-area').classList.add('moved');
                document.querySelector('.chat-messages').classList.add('visible');
                isFirstMessage = false;
            }

            // 增加消息计数器
            messageCounter++;
            console.log("添加第 " + messageCounter + " 条消息");

            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'message-right' : 'message-left'}`;
            
            // 生成标记，传递 isNewInput 参数
            const messageId = messageTree.addNode(text, parentId, isRetry, isUser, isPartial, isNewInput);
            messageDiv.setAttribute('data-id', messageId);
            messageDiv.setAttribute('data-counter', messageCounter);
            
            // 修改标号显示逻辑
            if (!isUser && !text.startsWith("再试一次润色：") && !text.startsWith("重新润色指定区域：")) {
                const markerDiv = document.createElement('div');
                markerDiv.className = 'message-marker';
                markerDiv.textContent = messageId; // 直接显示完整的标号
                messageDiv.appendChild(markerDiv);
            }
            
            // 添加发送者名称
            const senderDiv = document.createElement('div');
            senderDiv.className = 'message-sender';
            senderDiv.textContent = isUser ? '我' : '润色智能体';
            messageDiv.appendChild(senderDiv);
            
            // 创建消息内容容器
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.innerHTML = text; // 使用 innerHTML 来保留 HTML 标记
            messageDiv.appendChild(contentDiv);
            
            // 添加字数统计
            const statsDiv = document.createElement('div');
            statsDiv.className = 'message-stats';
            
            // 计算纯文本字数（不包含昵称和前缀）
            const plainText = text.replace(/<[^>]*>/g, '')  // 移除HTML标签
                                 .replace(/^.*[：:】\]\)\-]\s*/g, '')  // 移除前缀
                                 .replace(/\s+/g, '');  // 移除空白字符

            statsDiv.innerHTML = `${plainText.length}字`;
            
            messageDiv.appendChild(statsDiv);
            
            // 恢复为线性结构，始终添加到消息容器末尾
            messagesContainer.appendChild(messageDiv);
            
            // 如果是AI消息，添加操作按钮
            if (!isUser) {
                const actionsDiv = document.createElement('div');
                actionsDiv.className = 'message-actions';
                
                // 再试一次按钮
                const retryButton = document.createElement('button');
                retryButton.className = 'action-button';
                retryButton.innerHTML = `
                    <svg viewBox="0 0 24 24" fill="currentColor">
                        <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
                    </svg>
                    <span>再试一次</span>
                `;
                
                retryButton.onclick = async (e) => {
                    e.stopPropagation();
                    const currentText = contentDiv.innerHTML;
                    const currentMessageId = messageDiv.getAttribute('data-id');
                    const treeVisible = document.getElementById('treeContainer').style.display === 'flex';
                    
                    await addMessage("再试一次润色：" + currentText, true, currentMessageId, true, false, false);
                    
                    try {
                        submitBtn.disabled = true;
                        const response = await fetch('/polish', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ 
                                text: currentText,
                                style: getSelectedKeywords().length > 0 ? generatePrompt('', getSelectedKeywords()).style : ''
                            })
                        });

                        const data = await response.json();
                        if (data.error) throw new Error(data.error);
                        
                        // 传递当前消息ID作为父ID，确保结果添加到正确的树层级
                        await addMessage(data.modified_text, false, currentMessageId, true, false, false);
                        
                        // 如果树之前是显示的，确保它保持显示状态
                        if (treeVisible) {
                            const treeContainer = document.getElementById('treeContainer');
                            treeContainer.style.display = 'flex';
                            document.querySelector('.main-content').classList.add('tree-visible');
                            messageTree.render();
                        }
                        
                    } catch (error) {
                        console.error('Error:', error);
                        await addMessage(`润色失败: ${error.message}`, false);
                    } finally {
                        submitBtn.disabled = false;
                    }
                };
                
                // 导出文件按钮
                const exportButton = document.createElement('button');
                exportButton.className = 'action-button export-button';
                exportButton.innerHTML = `
                    <svg viewBox="0 0 24 24" fill="currentColor">
                        <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
                    </svg>
                    <span>导出文件</span>
                `;
                
                exportButton.onclick = (e) => {
                    e.stopPropagation();
                    // 获取当前消息内容
                    const textToExport = contentDiv.innerHTML;
                    
                    // 显示导出选项模态窗口
                    showExportModal(textToExport);
                };
                
                actionsDiv.appendChild(retryButton);
                actionsDiv.appendChild(exportButton);
                messageDiv.appendChild(actionsDiv);
                
                // 使文本可点击
                makeTextClickable(messageDiv);
            }
            
            // 如果是对某个节点的回复，自动展开该节点
            if (parentId && parentId !== "0" && window.treeNodeState) {
                // 确保父节点处于展开状态
                window.treeNodeState[parentId] = 'expanded';
            }
            
            // 更新文字思维导图
            updateTextTree();
            
            // 滚动到底部
            function scrollToBottom() {
                const messagesContainer = document.getElementById('chatMessages');
                if (messagesContainer) {
                    // 首先尝试正常滚动
                    messagesContainer.scrollTop = messagesContainer.scrollHeight + 2000;
                }
            }
            
            scrollToBottom();
            setTimeout(scrollToBottom, 100);
            setTimeout(scrollToBottom, 300);
            setTimeout(scrollToBottom, 500);
            
            /* 在窗口大小变化时重新调整滚动位置 */
            window.addEventListener('resize', function() {
                // 延迟执行，确保布局调整完成
                setTimeout(scrollToBottom, 200);
            });
        }

        const submitBtn = document.getElementById('submit');

        function makeTextClickable(element) {
            const clickableElements = element.querySelectorAll('del, span[style*="color: blue"], span[style*="background-color"]');
            
            clickableElements.forEach(element => {
                element.classList.add('clickable');
                
                element.addEventListener('click', async () => {
                    const textToPolish = element.textContent;
                    const parentMessage = element.closest('.message-content');
                    const fullText = parentMessage.innerHTML;
                    const treeVisible = document.getElementById('treeContainer').style.display === 'flex';
                    
                    // 获取消息ID
                    const messageElement = element.closest('.message');
                    if (!messageElement) {
                        console.error("找不到父消息元素");
                        return;
                    }
                    
                    const parentId = messageElement.getAttribute('data-id');
                    if (!parentId) {
                        console.error("找不到父消息ID");
                        return;
                    }
                    
                    const prefixedText = `重新润色指定区域：${textToPolish}`;
                    
                    // 添加用户消息，不是新输入
                    const newMessageId = await addMessage(prefixedText, true, parentId, false, false, false);

                    try {
                        const response = await fetch('/polish', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ 
                                text: textToPolish,
                                style: getSelectedKeywords().length > 0 ? generatePrompt('', getSelectedKeywords()).style : ''
                            })
                        });

                        const data = await response.json();
                        
                        if (data.error) {
                            throw new Error(data.error);
                        }
                        
                        // 替换原文中的对应部分，保持HTML标记
                        const newText = fullText.replace(element.outerHTML, data.modified_text);
                        
                        // 添加回复消息，确保它作为newMessageId的子节点
                        await addMessage(newText, false, newMessageId, false, true, false);
                        
                        // 如果树之前是显示的，确保它保持显示状态
                        if (treeVisible) {
                            const treeContainer = document.getElementById('treeContainer');
                            treeContainer.style.display = 'flex';
                            document.querySelector('.main-content').classList.add('tree-visible');
                            messageTree.render();
                        }
                        
                    } catch (error) {
                        console.error('Error:', error);
                        await addMessage(`润色失败: ${error.message}`, false);
                    }
                });
            });
        }

        const keywords = document.querySelectorAll('.keyword-btn');
        keywords.forEach(btn => {
            btn.addEventListener('click', () => {
                btn.classList.toggle('active');
            });
        });

        function getSelectedKeywords() {
            const selected = [];
            document.querySelectorAll('.keyword-btn.active').forEach(btn => {
                selected.push(btn.dataset.type);
            });
            return selected;
        }

        // 获取选择的专业领域
        function getSelectedDomain() {
            return document.getElementById('domain-select').value;
        }

        // 修改generatePrompt函数，加入专业领域
        function generatePrompt(text, keywords) {
            let styleGuide = '';
            if (keywords.includes('emotional')) {
                styleGuide += '更加感性和富有情感，';
            }
            if (keywords.includes('rigorous')) {
                styleGuide += '更加严谨和专业，';
            }
            if (keywords.includes('expand')) {
                styleGuide += '适当扩充内容，';
            }
            if (keywords.includes('compress')) {
                styleGuide += '精简表达，';
            }
            
            return {
                text: text,
                style: styleGuide.slice(0, -1),
                domain: getSelectedDomain(),
                textStyle: document.getElementById('style-select').value
            };
        }

        // 添加创建分割线的函数
        function addDivider(text = "新话题") {
            const messagesContainer = document.getElementById('chatMessages');
            
            // 创建分割线元素
            const divider = document.createElement('div');
            divider.className = 'message-divider';
            divider.innerHTML = `<span>${text}</span>`;
            divider.setAttribute('data-divider', 'true');
            
            // 将分割线添加到消息列表
            messagesContainer.appendChild(divider);
            
            // 分割线前的内容设为禁用状态
            const messages = document.querySelectorAll('.message');
            messages.forEach(msg => {
                msg.setAttribute('data-disabled', 'true');
                msg.classList.add('disabled-message');
                
                // 清除按钮和交互
                const retryBtn = msg.querySelector('.action-button');
                if (retryBtn) retryBtn.remove();
                
                const clickableElements = msg.querySelectorAll('.clickable');
                clickableElements.forEach(el => {
                    el.classList.remove('clickable');
                    el.style.cursor = 'default';
                    // 克隆并替换以移除所有事件
                    const newEl = el.cloneNode(true);
                    el.parentNode.replaceChild(newEl, el);
                });
            });
            
            // 完全重置消息树，抛弃之前的所有节点
            messageTree.resetTree();
            
            // 更新文字思维导图
            updateTextTree();
        }

        // 重置消息树，只保留新内容
        function resetMessageTreeAfterDivider() {
            // 保存当前所有节点
            const allNodes = [...messageTree.nodes];
            
            // 找到分割线后的消息，获取它们的ID
            const activeMsgIds = new Set();
            let foundDivider = false;
            
            // 遍历DOM中的所有消息和分割线元素
            const elements = document.querySelectorAll('.message, .message-divider');
            for (const el of elements) {
                if (el.classList.contains('message-divider')) {
                    foundDivider = true;
                    continue;
                }
                
                if (foundDivider && el.classList.contains('message')) {
                    const msgId = el.getAttribute('data-id');
                    if (msgId) {
                        activeMsgIds.add(msgId);
                    }
                }
            }
            
            // 如果没有分割线后的消息，则不需要重置
            if (activeMsgIds.size === 0) return;
            
            // 创建新的树结构，只包含分割线后的消息
            const newNodes = [];
            let nodeIdCounter = {};
            
            // 先添加根节点
            const rootNode = allNodes.find(node => node.id === "0");
            if (rootNode) {
                newNodes.push({...rootNode});
            }
            
            // 重新映射消息ID，保持结构但使用新的ID
            const idMapping = {"0": "0"}; // 根节点ID保持不变
            
            // 为每个活跃节点分配新ID
            for (const node of allNodes) {
                if (activeMsgIds.has(node.id)) {
                    // 提取级别
                    const parts = node.id.split('-');
                    const level = parseInt(parts[0]) || 1;
                    
                    // 初始化级别计数器
                    if (!nodeIdCounter[level]) {
                        nodeIdCounter[level] = 0;
                    }
                    
                    // 分配新ID
                    const newId = `${level}-${++nodeIdCounter[level]}`;
                    idMapping[node.id] = newId;
                }
            }
            
            // 更新DOM中消息的ID
            for (const el of document.querySelectorAll('.message')) {
                const oldId = el.getAttribute('data-id');
                if (activeMsgIds.has(oldId) && idMapping[oldId]) {
                    el.setAttribute('data-id', idMapping[oldId]);
                    // 更新标号显示
                    const marker = el.querySelector('.message-marker');
                    if (marker) {
                        marker.textContent = idMapping[oldId];
                    }
                }
            }
            
            // 为每个活跃节点创建新节点，使用新的ID和父ID映射
            for (const node of allNodes) {
                if (activeMsgIds.has(node.id)) {
                    const newNode = {...node};
                    newNode.id = idMapping[node.id];
                    
                    // 更新父ID
                    if (node.parentId && idMapping[node.parentId]) {
                        newNode.parentId = idMapping[node.parentId];
                    } else if (node.parentId === "0") {
                        newNode.parentId = "0";
                    } else {
                        newNode.parentId = null;
                    }
                    
                    newNodes.push(newNode);
                }
            }
            
            // 更新消息树
            messageTree.nodes = newNodes;
            messageTree.levelCounters = nodeIdCounter;
            messageTree.initD3Tree();
            messageTree.render();
            
            // 更新文字思维导图
            updateTextTree();
        }

        // 禁用分割线之前的所有消息
        function disablePreviousMessages(dividerElement) {
            let currentElement = dividerElement.previousElementSibling;
            
            while (currentElement) {
                // 标记为不可润色
                if (currentElement.classList.contains('message')) {
                    currentElement.setAttribute('data-disabled', 'true');
                    currentElement.classList.add('disabled-message');
                    
                    // 移除再试一次按钮
                    const retryButton = currentElement.querySelector('.action-button');
                    if (retryButton) {
                        retryButton.remove();
                    }
                    
                    // 移除可点击文本的点击事件
                    const clickableTexts = currentElement.querySelectorAll('.clickable');
                    clickableTexts.forEach(el => {
                        el.classList.remove('clickable');
                        el.style.cursor = 'default';
                        // 克隆元素以移除所有事件监听器
                        const newEl = el.cloneNode(true);
                        el.parentNode.replaceChild(newEl, el);
                    });
                }
                currentElement = currentElement.previousElementSibling;
            }
        }

        // 修复提交按钮的处理逻辑
        document.getElementById('submit').onclick = async function() {
            // 如果有文件上传，使用文件内容；否则使用输入框内容
            const inputText = document.getElementById('input').value.trim();
            
            // 检查是否有内容可提交
            if (!inputText && !fileContent) {
                alert('请输入需要润色的文本或上传文件');
                return;
            }
            
            // 优先使用输入框内容，如果输入框为空则使用文件内容
            const textToProcess = inputText || fileContent;
            const displayText = inputText || `上传文件: ${originalFilename}`;

            // 检查当前会话是否已有内容
            if (messageCounter > 0) {
                // 创建确认对话框
                const shouldCreateNew = confirm("当前会话已有内容，是否要新建会话？\n\n点击\"确定\"新建会话\n点击\"取消\"在当前会话中继续");
                
                if (shouldCreateNew) {
                    // 调用新建会话函数
                    createNewSession();
                } else {
                    // 在当前会话中添加分割线，并重置消息计数器
                    addDivider("新话题");
                    messageCounter = 0; // 重置消息计数器，让新消息从1开始
                }
            }

            submitBtn.disabled = true;
            
            try {
                // 用户从输入框发送新文本
                await addMessage(displayText, true, null, false, false, true);
                
                // 清空输入框
                document.getElementById('input').value = '';
                document.getElementById('input').style.height = '';

                const styleKeywords = getSelectedKeywords();
                const promptData = generatePrompt('', styleKeywords);

                const response = await fetch('/polish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        text: textToProcess,
                        style: promptData.style,
                        domain: promptData.domain,
                        textStyle: promptData.textStyle
                    })
                });

                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }

                const data = await response.json();

                if (data.error) {
                    throw new Error(data.error);
                }
                
                // 添加润色结果
                await addMessage(data.modified_text, false, "0", false, false, false);
                
                // 确保树被更新
                messageTree.render();
                
            } catch (error) {
                console.error('Error:', error);
                await addMessage(`润色失败: ${error.message}`, false, "0");
            } finally {
                submitBtn.disabled = false;
            }
        };

        // 同样更新retry按钮处理逻辑
        function updateRetryButtonHandler() {
            const messages = document.querySelectorAll('.message-left');
            messages.forEach(message => {
                const retryButton = message.querySelector('.action-button');
                if (retryButton) {
                    const originalClickHandler = retryButton.onclick;
                    retryButton.onclick = async (e) => {
                        e.stopPropagation();
                        const contentDiv = message.querySelector('.message-content');
                        const currentText = contentDiv.innerHTML;
                        const currentMessageId = message.getAttribute('data-id');
                        const treeVisible = document.getElementById('treeContainer').style.display === 'flex';
                        
                        await addMessage("再试一次润色：" + currentText, true, currentMessageId, true, false, false);
                        
                        try {
                            submitBtn.disabled = true;
                            
                            const styleKeywords = getSelectedKeywords();
                            const promptData = generatePrompt('', styleKeywords);

                            const response = await fetch('/polish', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ 
                                    text: currentText,
                                    style: promptData.style,
                                    domain: promptData.domain
                                })
                            });

                            const data = await response.json();
                            if (data.error) throw new Error(data.error);
                            
                            // 传递消息ID作为父ID，确保结果显示在正确的树结构位置
                            await addMessage(data.modified_text, false, currentMessageId, true, false, false);
                            
                            if (treeVisible) {
                                const treeContainer = document.getElementById('treeContainer');
                                treeContainer.style.display = 'flex';
                                document.querySelector('.main-content').classList.add('tree-visible');
                                messageTree.render();
                            }
                            
                        } catch (error) {
                            console.error('Error:', error);
                            await addMessage(`润色失败: ${error.message}`, false);
                        } finally {
                            submitBtn.disabled = false;
                        }
                    };
                }
            });
        }

        // 在文档加载完成后调用
        document.addEventListener('DOMContentLoaded', function() {
            updateRetryButtonHandler();
        });

        // 添加自动调整输入框高度的功能
        const textarea = document.getElementById('input');
        textarea.addEventListener('input', function() {
            this.style.height = '';
            this.style.height = Math.min(this.scrollHeight, 200) + 'px';
        });

        // 移除原有的水印 div
        document.querySelector('.watermark')?.remove();

        // 主题切换功能
        const themeToggle = document.getElementById('themeToggle');
        const lightIcon = document.getElementById('lightIcon');
        const darkIcon = document.getElementById('darkIcon');
        
        // 检查本地存储中的主题设置
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme === 'dark') {
            document.body.classList.add('dark-mode');
            lightIcon.style.display = 'none';
            darkIcon.style.display = 'block';
        }
        
        themeToggle.addEventListener('click', () => {
            document.body.classList.toggle('dark-mode');
            
            if (document.body.classList.contains('dark-mode')) {
                localStorage.setItem('theme', 'dark');
                lightIcon.style.display = 'none';
                darkIcon.style.display = 'block';
            } else {
                localStorage.setItem('theme', 'light');
                lightIcon.style.display = 'block';
                darkIcon.style.display = 'none';
            }
        });

        // 移动端菜单切换
        const mobileMenuToggle = document.getElementById('mobileMenuToggle');
        const sidebar = document.getElementById('sidebar');
        
        // 检测是否为移动设备
        function isMobile() {
            return window.innerWidth <= 768;
        }
        
        // 初始化移动端菜单
        function initMobileMenu() {
            if (isMobile()) {
                mobileMenuToggle.style.display = 'block';
            } else {
                mobileMenuToggle.style.display = 'none';
                sidebar.classList.remove('open');
            }
        }
        
        // 窗口大小变化时重新初始化
        window.addEventListener('resize', initMobileMenu);
        
        // 点击菜单按钮切换侧边栏
        mobileMenuToggle.addEventListener('click', () => {
            sidebar.classList.toggle('open');
        });
        
        // 初始化
        initMobileMenu();

        // 当窗口大小改变时重新渲染树
        window.addEventListener('resize', function() {
            if (messageTree && messageTree.nodes.length > 0) {
                // 重新初始化树并渲染
                messageTree.initD3Tree();
                messageTree.render();
            }
        });

        // 添加文字思维导图更新函数
        function updateTextTree() {
            const textTree = document.getElementById('textTree');
            textTree.innerHTML = '';
            
            // 跟踪节点折叠状态
            if (!window.treeNodeState) {
                window.treeNodeState = {};
            }
            
            // 按树形结构组织节点
            const organizeNodes = (nodes) => {
                // 创建节点映射
                const nodeMap = {};
                nodes.forEach(node => {
                    if (!nodeMap[node.id]) {
                        nodeMap[node.id] = {
                            ...node,
                            children: []
                        };
                    }
                });
                
                // 构建树形结构
                const rootNodes = [];
                nodes.forEach(node => {
                    if (node.parentId && nodeMap[node.parentId]) {
                        nodeMap[node.parentId].children.push(nodeMap[node.id]);
                    } else if (node.id === "0" || !node.parentId) {
                        rootNodes.push(nodeMap[node.id]);
                    }
                });
                
                return rootNodes;
            };
            
            // 递归创建节点的显示
            const createNodeDiv = (node, level) => {
                const itemDiv = document.createElement('div');
                itemDiv.className = 'text-tree-item';
                itemDiv.setAttribute('data-id', node.id);
                
                // 创建节点容器，包含按钮和内容
                const nodeContainer = document.createElement('div');
                nodeContainer.className = 'text-tree-node-container';
                
                // 如果有子节点，添加折叠/展开按钮
                if (node.children && node.children.length > 0) {
                    const toggleBtn = document.createElement('button');
                    toggleBtn.className = 'text-tree-toggle';
                    
                    // 检查节点状态
                    const isCollapsed = window.treeNodeState[node.id] === 'collapsed';
                    
                    // 使用SVG图标
                    const svgIcon = isCollapsed ? 
                        `<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                            <polyline points="9 18 15 12 9 6"></polyline>
                        </svg>` :
                        `<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                            <polyline points="6 9 12 15 18 9"></polyline>
                        </svg>`;
                        
                    toggleBtn.innerHTML = svgIcon;
                    toggleBtn.title = isCollapsed ? '展开' : '折叠';
                    toggleBtn.setAttribute('aria-label', isCollapsed ? '展开' : '折叠');
                    
                    toggleBtn.onclick = (e) => {
                        e.stopPropagation(); // 防止触发节点点击事件
                        
                        // 切换节点状态
                        const currentState = window.treeNodeState[node.id];
                        const newState = currentState === 'collapsed' ? 'expanded' : 'collapsed';
                        window.treeNodeState[node.id] = newState;
                        
                        // 更新思维导图
                        updateTextTree();
                    };
                    
                    nodeContainer.appendChild(toggleBtn);
                } else {
                    // 如果没有子节点，添加占位符保持对齐
                    const spacer = document.createElement('span');
                    spacer.className = 'text-tree-spacer';
                    spacer.innerHTML = '&nbsp;&nbsp;';
                    nodeContainer.appendChild(spacer);
                }
                
                // 计算缩进级别
                itemDiv.style.marginLeft = `${level * 20}px`;
                
                // 显示节点内容预览
                const preview = node.content.replace(/<[^>]*>/g, '').substring(0, 50);
                const formattedId = node.id === "0" ? "根节点" : node.id;
                
                // 创建标题和预览的容器
                const contentDiv = document.createElement('div');
                contentDiv.className = 'text-tree-content';
                
                const titleSpan = document.createElement('span');
                titleSpan.style.fontWeight = 'bold';
                titleSpan.textContent = formattedId + ": ";
                
                const previewSpan = document.createElement('span');
                previewSpan.textContent = preview + (preview.length >= 50 ? '...' : '');
                
                contentDiv.appendChild(titleSpan);
                contentDiv.appendChild(previewSpan);
                
                // 将内容添加到节点容器
                nodeContainer.appendChild(contentDiv);
                
                // 将节点容器添加到主div
                itemDiv.appendChild(nodeContainer);
                
                // 添加悬停提示
                itemDiv.title = node.content.replace(/<[^>]*>/g, '');
                
                // 点击节点内容跳转到对应消息
                contentDiv.onclick = () => {
                    // 使用增强的scrollToMessage方法
                    messageTree.scrollToMessage(node.id);
                    
                    // 高亮当前项
                    document.querySelectorAll('.text-tree-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    itemDiv.classList.add('active');
                    
                    // 同时高亮树中对应的节点
                    messageTree.setActiveNode(node.id);
                    messageTree.render();
                };
                
                return itemDiv;
            };
            
            // 递归添加节点
            const addNodeToTree = (container, node, level) => {
                const nodeDiv = createNodeDiv(node, level);
                container.appendChild(nodeDiv);
                
                // 检查节点是否折叠
                const isCollapsed = window.treeNodeState[node.id] === 'collapsed';
                
                // 递归处理子节点，如果没有折叠
                if (node.children && node.children.length > 0 && !isCollapsed) {
                    // 创建子节点容器
                    const childrenContainer = document.createElement('div');
                    childrenContainer.className = 'text-tree-children';
                    container.appendChild(childrenContainer);
                    
                    node.children.forEach(child => {
                        addNodeToTree(childrenContainer, child, level + 1);
                    });
                }
            };
            
            // 组织节点并显示
            const organizedNodes = organizeNodes(messageTree.nodes);
            organizedNodes.forEach(node => {
                addNodeToTree(textTree, node, 0);
            });
        }

        // 修改文件上传处理逻辑
        let uploadedFile = null;
        let originalFilename = '';
        let fileContent = '';  // 存储文件内容

        document.getElementById('file-input').addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // 文件类型检查
            const fileExt = file.name.split('.').pop().toLowerCase();
            const allowedTypes = ['txt', 'doc', 'docx', 'pdf'];
            if (!allowedTypes.includes(fileExt)) {
                alert('不支持的文件类型，请上传txt、doc、docx或pdf文件');
                this.value = '';
                return;
            }
            
            uploadedFile = file;
            originalFilename = file.name;
            
            // 显示文件信息（仅显示文件名）
            const fileInfo = document.getElementById('fileInfo');
            const fileName = document.getElementById('fileName');
            
            fileName.textContent = file.name;
            fileInfo.style.display = 'block';
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                submitBtn.disabled = true;
                
                // 显示加载状态
                document.getElementById('input').placeholder = "正在解析文件内容...";
                
                const response = await fetch('/upload-file', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.error) {
                    throw new Error(data.error);
                }
                
                // 存储文件内容
                fileContent = data.content;
                
                // 重置文件预览的加载状态
                const filePreview = document.getElementById('filePreview');
                filePreview.innerHTML = '';
                filePreview.classList.remove('loaded');
                
                // 显示导出按钮，但文件上传后不立即显示
                updateExportButtonsVisibility(false);
                
                // 恢复输入框提示
                document.getElementById('input').placeholder = "请输入需要润色的文本...";
                
            } catch (error) {
                console.error('Error:', error);
                alert(`文件处理失败: ${error.message}`);
                resetFileUpload();
            } finally {
                submitBtn.disabled = false;
            }
        });

        // 自动处理文件内容的函数
        async function processFileContent() {
            if (!fileContent) return;
            
            submitBtn.disabled = true;
            
            try {
                // 用户从文件上传文本
                await addMessage(`上传文件: ${originalFilename}`, true, null, false, false, true);

                const styleKeywords = getSelectedKeywords();
                const promptData = generatePrompt('', styleKeywords);

                const response = await fetch('/polish', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 
                        text: fileContent,
                        style: promptData.style,
                        domain: promptData.domain,
                        textStyle: promptData.textStyle
                    })
                });

                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }

                const data = await response.json();

                if (data.error) {
                    throw new Error(data.error);
                }
                
                // 添加润色结果
                await addMessage(data.modified_text, false, "0", false, false, false);
                
                // 确保树被更新
                messageTree.render();
                
            } catch (error) {
                console.error('Error:', error);
                await addMessage(`润色失败: ${error.message}`, false, "0");
            } finally {
                submitBtn.disabled = false;
            }
        }

        // 改进文件预览功能，保留原始样式
        document.getElementById('fileName').addEventListener('click', function() {
            const filePreview = document.getElementById('filePreview');
            
            // 检查是否已加载预览内容
            if (!filePreview.classList.contains('loaded')) {
                // 格式化预览内容
                const formattedContent = formatPreviewContent(fileContent);
                filePreview.innerHTML = formattedContent;
                filePreview.classList.add('loaded');
            }
            
            // 切换显示状态
            filePreview.classList.toggle('active');
        });

        // 格式化预览内容，保留基本的段落和结构
        function formatPreviewContent(content) {
            if (!content) return '';
            
            // 如果内容过长则截断
            const maxLength = 5000;
            const truncated = content.length > maxLength ? 
                content.substring(0, maxLength) + '...' : content;
            
            // 处理段落
            return truncated
                .replace(/\n{2,}/g, '</p><p>') // 多行换行转为段落
                .replace(/\n/g, '<br>') // 单行换行转为<br>
                .replace(/</g, '&lt;').replace(/>/g, '&gt;') // 转义HTML标签
                .split('</p><p>').map(p => `<p>${p}</p>`).join(''); // 包装段落
        }

        // 修改上传文件处理，优化工作流程
        document.getElementById('file-input').addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // 文件类型检查
            const fileExt = file.name.split('.').pop().toLowerCase();
            const allowedTypes = ['txt', 'doc', 'docx', 'pdf'];
            if (!allowedTypes.includes(fileExt)) {
                alert('不支持的文件类型，请上传txt、doc、docx或pdf文件');
                this.value = '';
                return;
            }
            
            uploadedFile = file;
            originalFilename = file.name;
            
            // 显示文件信息（仅显示文件名）
            const fileInfo = document.getElementById('fileInfo');
            const fileName = document.getElementById('fileName');
            
            fileName.textContent = file.name;
            fileInfo.style.display = 'block';
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                submitBtn.disabled = true;
                
                // 显示加载状态
                document.getElementById('input').placeholder = "正在处理文件内容...";
                
                const response = await fetch('/upload-file', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.error) {
                    throw new Error(data.error);
                }
                
                // 存储文件内容
                fileContent = data.content;
                
                // 重置文件预览的加载状态
                document.getElementById('filePreview').classList.remove('loaded');
                
                // 显示导出按钮
                updateExportButtonsVisibility(true);
                
                // 恢复输入框提示
                document.getElementById('input').placeholder = "请输入需要润色的文本...";
                
                // 检查当前会话是否已有内容
                if (messageCounter > 0) {
                    // 创建确认对话框
                    const shouldCreateNew = confirm("当前会话已有内容，是否要新建会话？\n\n点击\"确定\"新建会话\n点击\"取消\"在当前会话中继续");
                    
                    if (shouldCreateNew) {
                        // 调用新建会话函数
                        createNewSession();
                    } else {
                        // 在当前会话中添加分割线，并重置消息计数器
                        addDivider("新文件上传");
                        messageCounter = 0; // 重置消息计数器，让新消息从1开始
                    }
                }
                
                // 自动提交润色
                await processFileContent();
                
            } catch (error) {
                console.error('Error:', error);
                alert(`文件处理失败: ${error.message}`);
                resetFileUpload();
            } finally {
                submitBtn.disabled = false;
            }
        });

        // 修改文件移除函数，彻底清理状态
        document.getElementById('removeFile').addEventListener('click', function() {
            resetFileUpload();
            updateExportButtonsVisibility(false);
            document.getElementById('input').placeholder = "请输入需要润色的文本...";
            
            // 关闭文件预览
            const filePreview = document.getElementById('filePreview');
            filePreview.classList.remove('active');
            filePreview.classList.remove('loaded');
            filePreview.innerHTML = '';
        });

        // 完善重置文件上传功能
        function resetFileUpload() {
            document.getElementById('fileInfo').style.display = 'none';
            document.getElementById('file-input').value = '';
            fileContent = '';
            uploadedFile = null;
            originalFilename = '';
        }

        // 修复导出下拉菜单点击事件
        document.addEventListener('click', function(event) {
            const exportOptions = document.getElementById('exportOptions');
            const exportBtn = document.getElementById('exportBtn');
            
            if (!exportBtn.contains(event.target) && !exportOptions.contains(event.target)) {
                exportOptions.style.display = 'none';
            }
        });

        // 确保所有按钮点击后关闭导出下拉菜单
        document.getElementById('exportDocx').addEventListener('click', function(e) {
            e.stopPropagation();
            exportLastMessage('docx');
            document.getElementById('exportOptions').style.display = 'none';
        });

        document.getElementById('exportPdf').addEventListener('click', function(e) {
            e.stopPropagation();
            exportLastMessage('pdf');
            document.getElementById('exportOptions').style.display = 'none';
        });

        document.getElementById('exportTxt').addEventListener('click', function(e) {
            e.stopPropagation();
            exportLastMessage('txt');
            document.getElementById('exportOptions').style.display = 'none';
        });

        // 更新导出按钮可见性
        function updateExportButtonsVisibility(visible) {
            const exportBtn = document.getElementById('exportBtn');
            exportBtn.style.display = visible ? 'inline-flex' : 'none';
        }

        // 初始化导出按钮状态（隐藏）
        updateExportButtonsVisibility(false);

        // 添加文档加载完成时的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 更新所有消息的retry按钮处理
            updateRetryButtonHandler();
            
            // 隐藏导出按钮
            updateExportButtonsVisibility(false);
            
            // 检查窗口大小并适配移动端
            initMobileMenu();
            
            // 初始化树结构
            if (messageTree && messageTree.nodes.length > 0) {
                messageTree.initD3Tree();
                messageTree.render();
            }
            
            // 检查并恢复主题设置
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme === 'dark') {
                document.body.classList.add('dark-mode');
                document.getElementById('lightIcon').style.display = 'none';
                document.getElementById('darkIcon').style.display = 'block';
            }
        });

        // 优化窗口大小变化处理
        let resizeTimeout;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                // 检查移动端菜单
                initMobileMenu();
                
                // 重新渲染树
                if (messageTree && messageTree.nodes.length > 0) {
                    messageTree.initD3Tree();
                    messageTree.render();
                }
            }, 300);
        });

        // 修复导出下拉菜单显示问题
        document.getElementById('exportBtn').addEventListener('click', function(e) {
            e.stopPropagation();
            const exportOptions = document.getElementById('exportOptions');
            
            // 切换显示状态
            if (exportOptions.style.display === 'block') {
                exportOptions.style.display = 'none';
            } else {
                exportOptions.style.display = 'block';
                
                // 确保菜单在视口内可见
                const rect = exportOptions.getBoundingClientRect();
                if (rect.top < 0) {
                    // 如果顶部超出视口，改为向下显示
                    exportOptions.style.bottom = 'auto';
                    exportOptions.style.top = '100%';
                    exportOptions.style.marginTop = '8px';
                    exportOptions.style.marginBottom = '0';
                }
            }
        });

        // 导出文件功能
        async function exportFile(text, format) {
            try {
                submitBtn.disabled = true;
                
                // 清理HTML标签，为PDF导出准备纯文本内容
                let cleanText = text;
                if (format === 'pdf' || format === 'txt' || format === 'docx') {
                    // 保留修改标记但转换为纯文本
                    cleanText = text
                        .replace(/<del>(.*?)<\/del>/g, '【删除: $1】')
                        .replace(/<span style="color: blue;">(.*?)<\/span>/g, '【新增: $1】')
                        .replace(/<span style="background-color: #90EE90;">(.*?)<\/span>/g, '【修改: $1】')
                        .replace(/<[^>]*>/g, ''); // 移除其他HTML标签
                }
                
                const response = await fetch('/export', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        text: cleanText,
                        format: format,
                        filename: originalFilename || 'document'
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`服务器响应错误: ${response.status}`);
                }
                
                // 创建下载链接
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                
                // 设置文件名
                const fileExtension = format === 'docx' ? '.docx' : format === 'pdf' ? '.pdf' : '.txt';
                const baseFilename = originalFilename ? originalFilename.split('.')[0] : 'document';
                a.download = `${baseFilename}_润色后${fileExtension}`;
                
                a.href = url;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                a.remove();
                
            } catch (error) {
                console.error('导出失败:', error);
                alert(`导出失败: ${error.message}`);
            } finally {
                submitBtn.disabled = false;
            }
        }

        // 导出最新润色结果
        function exportLastMessage(format) {
            // 找到最后一条AI消息
            const aiMessages = document.querySelectorAll('.message-left');
            if (aiMessages.length === 0) {
                alert('没有可导出的润色结果');
                return;
            }
            
            const lastAiMessage = aiMessages[aiMessages.length - 1];
            const contentDiv = lastAiMessage.querySelector('.message-content');
            
            if (contentDiv) {
                exportFile(contentDiv.innerHTML, format);
            } else {
                alert('无法获取润色内容');
            }
        }

        // 修复导出按钮处理
        document.getElementById('exportDocx').addEventListener('click', function(e) {
            e.stopPropagation();
            exportLastMessage('docx');
            document.getElementById('exportOptions').style.display = 'none';
        });

        document.getElementById('exportPdf').addEventListener('click', function(e) {
            e.stopPropagation();
            exportLastMessage('pdf');
            document.getElementById('exportOptions').style.display = 'none';
        });

        document.getElementById('exportTxt').addEventListener('click', function(e) {
            e.stopPropagation();
            exportLastMessage('txt');
            document.getElementById('exportOptions').style.display = 'none';
        });

        // 点击文档其他地方关闭导出菜单
        document.addEventListener('click', function(event) {
            const exportOptions = document.getElementById('exportOptions');
            const exportBtn = document.getElementById('exportBtn');
            
            if (!exportBtn.contains(event.target) && !exportOptions.contains(event.target)) {
                exportOptions.style.display = 'none';
            }
        });

        // 确保导出按钮的显示状态
        function updateExportButtonsVisibility(visible) {
            const exportBtn = document.getElementById('exportBtn');
            if (exportBtn) {
                exportBtn.style.display = visible ? 'flex' : 'none';
            }
        }

        // DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始隐藏导出按钮
            updateExportButtonsVisibility(false);
            
            // 其他初始化...
        });

        // 修改文件预览为悬停模式
        document.getElementById('fileName').addEventListener('mouseenter', function() {
            const filePreview = document.getElementById('filePreview');
            
            // 检查是否已加载预览内容
            if (!filePreview.classList.contains('loaded')) {
                // 格式化预览内容
                const formattedContent = formatPreviewContent(fileContent);
                filePreview.innerHTML = formattedContent;
                filePreview.classList.add('loaded');
            }
            
            // 显示预览
            filePreview.style.display = 'block';
        });

        document.getElementById('fileName').addEventListener('mouseleave', function(e) {
            // 检查鼠标是否移到了预览框上
            const filePreview = document.getElementById('filePreview');
            const rect = filePreview.getBoundingClientRect();
            
            if (
                e.clientX < rect.left || 
                e.clientX > rect.right || 
                e.clientY < rect.top || 
                e.clientY > rect.bottom
            ) {
                // 如果鼠标不是移动到预览框上，则隐藏预览框
                filePreview.style.display = 'none';
            }
        });

        // 给预览框也添加鼠标离开事件
        document.getElementById('filePreview').addEventListener('mouseleave', function() {
            this.style.display = 'none';
        });

        // 添加回车发送功能
        textarea.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault(); // 阻止默认的换行行为
                const text = this.value.trim();
                if (text) {
                    submitBtn.click(); // 触发发送按钮点击事件
                }
            }
        });

        // 原始事件处理器移除
        document.getElementById('newChatBtn').addEventListener('click', function() {
            if (confirm('是否开始新会话？这将清空当前会话内容。')) {
                // 清空聊天记录
                document.getElementById('chatMessages').innerHTML = '';
                
                // 重置消息计数器
                messageCounter = 0;
                
                // 重置输入框
                document.getElementById('input').value = '';
                
                // 重置消息树
                messageTree.nodes = [];
                messageTree.render();
                
                // 重置输入区域位置
                document.querySelector('.input-area').classList.remove('moved');
                document.querySelector('.chat-messages').classList.remove('visible');
                isFirstMessage = true;
            }
        });
        
        // 移除历史记录按钮点击事件
        // document.getElementById('historyBtn').addEventListener('click', function() {
        //     alert('历史记录功能正在开发中...');
        // });

        // 添加会话管理功能
        const newChatBtn = document.getElementById('newChatBtn');
        // const historyBtn = document.getElementById('historyBtn'); // 移除历史记录按钮引用
        const historyList = document.getElementById('historyItems');

        // 生成唯一会话ID
        function generateSessionId() {
            return Date.now().toString(36) + Math.random().toString(36).substr(2);
        }

        // 保存当前会话
        function saveCurrentSession() {
            if (messageCounter === 0) return null; // 没有消息不保存
            
            try {
                const sessionData = getCurrentSessionData();
                const sessions = getStoredSessions();
                
                // 检查是否已存在相同ID的会话，有则更新
                const existingIndex = sessions.findIndex(s => s.id === sessionData.id);
                if (existingIndex !== -1) {
                    sessions[existingIndex] = sessionData;
                } else {
                    sessions.push(sessionData);
                }
                
                // 保存会话
                localStorage.setItem('chatSessions', JSON.stringify(sessions));
                console.log("保存会话: " + sessionData.id);
                
                // 更新历史记录列表
                updateHistoryList();
                return sessionData.id;
            } catch (error) {
                console.error("保存会话失败:", error);
                alert("无法保存会话，可能是浏览器存储空间不足。");
                return null;
            }
        }

        // 获取存储的所有会话
        function getStoredSessions() {
            try {
                const sessionsJson = localStorage.getItem('chatSessions');
                if (!sessionsJson) return [];
                
                const sessions = JSON.parse(sessionsJson);
                return Array.isArray(sessions) ? sessions : [];
            } catch (error) {
                console.error("读取会话失败:", error);
                return [];
            }
        }

        // 获取当前会话数据
        function getCurrentSessionData() {
            try {
                const messages = [];
                document.querySelectorAll('.message').forEach(msg => {
                    try {
                        const contentElement = msg.querySelector('.message-content');
                        if (!contentElement) return;
                        
                        const content = contentElement.innerHTML;
                        const isUser = msg.classList.contains('message-right');
                        const messageId = msg.getAttribute('data-id') || null;
                        const parentId = msg.getAttribute('data-parent-id') || null;
                        
                        messages.push({
                            content: content,
                            isUser: isUser,
                            messageId: messageId,
                            parentId: parentId
                        });
                    } catch (e) {
                        console.warn("处理单条消息失败:", e);
                    }
                });
                
                // 如果没有消息，返回一个基本对象
                if (messages.length === 0) {
                    return {
                        id: currentSessionId || generateSessionId(),
                        title: "新会话",
                        timestamp: Date.now(),
                        messages: []
                    };
                }
                
                // 提取标题（使用第一条用户消息或AI消息的前30个字符）
                let title = "新会话";
                const userMessage = messages.find(m => m.isUser);
                if (userMessage) {
                    // 去除HTML标签后提取文本
                    const plainText = userMessage.content.replace(/<[^>]*>/g, '');
                    title = plainText.substring(0, 30) + (plainText.length > 30 ? '...' : '');
                }
                
                return {
                    id: currentSessionId || generateSessionId(),
                    title: title,
                    timestamp: Date.now(),
                    messages: messages
                };
            } catch (error) {
                console.error("创建会话数据失败:", error);
                return {
                    id: currentSessionId || generateSessionId(),
                    title: "新会话 (错误)",
                    timestamp: Date.now(),
                    messages: []
                };
            }
        }

        // 加载会话
        function loadSession(sessionId) {
            try {
                if (!sessionId) return false;
                
                const sessions = getStoredSessions();
                const session = sessions.find(s => s.id === sessionId);
                
                if (!session || !session.messages || !Array.isArray(session.messages)) {
                    console.error("找不到有效会话:", sessionId);
                    return false;
                }
                
                // 清空当前聊天内容
                const chatMessages = document.getElementById('chatMessages');
                chatMessages.innerHTML = '';
                
                // 重置消息计数器
                messageCounter = 0;
                
                // 设置当前会话ID
                currentSessionId = session.id;
                
                // 重建消息树
                messageTree.nodes = [];
                messageTree.rootId = null;
                messageTree.levelCounters = {};
                messageTree.currentLevel = 0;
                messageTree.initD3Tree();
                
                console.log("加载会话:", sessionId, "消息数:", session.messages.length);
                
                // 加载消息
                if (session.messages.length > 0) {
                    try {
                        session.messages.forEach((msg, index) => {
                            // 确保第一条用户消息被标记为新输入
                            const isFirstUserMsg = index === 0 && msg.isUser;
                            addMessage(
                                msg.content, 
                                msg.isUser, 
                                msg.parentId, 
                                false, 
                                false, 
                                isFirstUserMsg
                            );
                        });
                        
                        // 确保聊天区域可见
                        document.querySelector('.input-area').classList.add('moved');
                        document.querySelector('.chat-messages').classList.add('visible');
                        isFirstMessage = false;
                    } catch (e) {
                        console.error("加载消息失败:", e);
                        alert("部分消息可能未正确加载");
                    }
                }
                
                // 更新历史记录列表
                updateHistoryList();
                
                return true;
            } catch (error) {
                console.error("加载会话失败:", error);
                alert("加载会话失败: " + error.message);
                return false;
            }
        }

        // 删除会话
        function deleteSession(sessionId) {
            try {
                if (!sessionId) return false;
                
                let sessions = getStoredSessions();
                const initialCount = sessions.length;
                sessions = sessions.filter(s => s.id !== sessionId);
                
                // 保存更新后的会话列表
                localStorage.setItem('chatSessions', JSON.stringify(sessions));
                console.log(`删除会话: ${sessionId}, 剩余会话数: ${sessions.length}`);
                
                // 刷新会话列表
                updateHistoryList();
                
                // 如果删除的是当前会话，则创建新会话
                if (sessionId === currentSessionId) {
                    createNewSession();
                }
                
                return sessions.length !== initialCount;
            } catch (error) {
                console.error("删除会话失败:", error);
                alert("删除会话失败: " + error.message);
                return false;
            }
        }

        // 更新历史会话列表
        function updateHistoryList() {
            try {
                const sessions = getStoredSessions();
                const historyList = document.getElementById('historyItems');
                
                if (!historyList) {
                    console.error("找不到历史记录容器");
                    return;
                }
                
                // 更新历史记录数量显示
                const historyTitle = document.querySelector('.history-section-title');
                if (historyTitle) {
                    historyTitle.setAttribute('data-count', sessions.length.toString());
                }
                
                historyList.innerHTML = '';
                
                // 按时间倒序排列
                sessions.sort((a, b) => b.timestamp - a.timestamp);
                
                if (sessions.length === 0) {
                    historyList.innerHTML = '<div class="empty-history">暂无历史会话</div>';
                    return;
                }
                
                sessions.forEach(session => {
                    try {
                        const sessionItem = document.createElement('div');
                        sessionItem.className = 'history-item';
                        if (session.id === currentSessionId) {
                            sessionItem.classList.add('active');
                        }
                        
                        // 创建标题
                        const title = document.createElement('div');
                        title.className = 'history-title';
                        title.textContent = session.title || "未命名会话";
                        
                        // 创建日期
                        const date = document.createElement('div');
                        date.className = 'history-date';
                        date.textContent = formatDate(session.timestamp);
                        
                        // 创建删除按钮
                        const deleteBtn = document.createElement('button');
                        deleteBtn.className = 'history-delete-btn';
                        deleteBtn.innerHTML = '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/></svg>';
                        deleteBtn.title = '删除此会话';
                        
                        // 添加到会话项
                        sessionItem.appendChild(title);
                        sessionItem.appendChild(date);
                        sessionItem.appendChild(deleteBtn);
                        
                        // 点击会话项加载对应会话
                        sessionItem.addEventListener('click', (e) => {
                            if (!e.target.closest('.history-delete-btn')) {
                                loadSession(session.id);
                            }
                        });
                        
                        // 点击删除按钮删除会话
                        deleteBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            if (confirm('确定要删除此会话吗？')) {
                                deleteSession(session.id);
                            }
                        });
                        
                        // 添加到列表
                        historyList.appendChild(sessionItem);
                    } catch (e) {
                        console.warn("创建历史记录项失败:", e);
                    }
                });
                
                console.log("更新历史记录列表, 会话数:", sessions.length);
            } catch (error) {
                console.error("更新历史记录列表失败:", error);
            }
        }

        // 格式化日期
        function formatDate(timestamp) {
            try {
                const date = new Date(timestamp);
                const now = new Date();
                const diff = now - date;
                
                // 今天的消息只显示时间
                if (date.toDateString() === now.toDateString()) {
                    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                }
                
                // 昨天的消息显示"昨天"
                const yesterday = new Date(now);
                yesterday.setDate(now.getDate() - 1);
                if (date.toDateString() === yesterday.toDateString()) {
                    return '昨天 ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                }
                
                // 7天内的消息显示星期几
                if (diff < 7 * 24 * 60 * 60 * 1000) {
                    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
                    return '星期' + weekdays[date.getDay()] + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                }
                
                // 其他消息显示完整日期
                return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            } catch (error) {
                console.warn("格式化日期失败:", error);
                return "未知时间";
            }
        }

        // 创建新会话
        function createNewSession() {
            // 保存当前会话
            if (messageCounter > 0) {
                saveCurrentSession();
            }
            
            // 清空当前聊天内容
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.innerHTML = '';
            
            // 重置消息计数器和当前会话ID
            messageCounter = 0;
            currentSessionId = generateSessionId();
            
            // 重置消息树
            messageTree.nodes = [];
            messageTree.rootId = null;  // 确保重置根节点
            messageTree.levelCounters = {};  // 重置级别计数器
            messageTree.currentLevel = 0;  // 重置当前级别
            messageTree.initD3Tree();  // 重新初始化树
            messageTree.render();  // 渲染树
            
            // 重置文本思维导图
            updateTextTree();
            
            // 重置输入区域
            document.getElementById('input').value = '';
            document.querySelector('.input-area').classList.remove('moved');
            document.querySelector('.chat-messages').classList.remove('visible');
            isFirstMessage = true;
            
            // 重置文件上传状态
            resetFileUpload();
            
            // 重置关键词按钮
            document.querySelectorAll('.keyword-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 更新历史列表，取消当前活动项
            updateHistoryList();
            
            console.log("创建新会话: " + currentSessionId);
        }

        // 保存当前会话
        function saveCurrentSession() {
            if (messageCounter === 0) return null; // 没有消息不保存
            
            try {
                const sessionData = getCurrentSessionData();
                const sessions = getStoredSessions();
                
                // 检查是否已存在相同ID的会话，有则更新
                const existingIndex = sessions.findIndex(s => s.id === sessionData.id);
                if (existingIndex !== -1) {
                    sessions[existingIndex] = sessionData;
                } else {
                    sessions.push(sessionData);
                }
                
                // 保存会话
                localStorage.setItem('chatSessions', JSON.stringify(sessions));
                console.log("保存会话: " + sessionData.id);
                
                // 更新历史记录列表
                updateHistoryList();
                return sessionData.id;
            } catch (error) {
                console.error("保存会话失败:", error);
                alert("无法保存会话，可能是浏览器存储空间不足。");
                return null;
            }
        }

        // 设置自动保存
        function setupAutoSave() {
            // 添加消息后自动保存
            const originalAddMessage = addMessage;
            addMessage = function() {
                // 调用原始方法
                const result = originalAddMessage.apply(this, arguments);
                
                // 设置延迟保存，避免频繁保存
                clearTimeout(autoSaveTimeout);
                autoSaveTimeout = setTimeout(() => {
                    // 如果有currentSessionId，则更新现有会话而不是创建新会话
                    if (currentSessionId && messageCounter > 0) {
                        saveCurrentSession();
                    }
                }, 2000); // 2秒后自动保存
                
                return result;
            };
            
            // 每5分钟自动保存一次，但仅更新现有会话
            setInterval(() => {
                if (messageCounter > 0 && currentSessionId) {
                    console.log("定时自动保存会话");
                    saveCurrentSession();
                }
            }, 5 * 60 * 1000);
            
            // 在页面关闭/刷新前保存
            window.addEventListener('beforeunload', function() {
                if (messageCounter > 0 && currentSessionId) {
                    saveCurrentSession();
                }
            });
        }

        // 新建会话按钮事件
        newChatBtn.addEventListener('click', function() {
            createNewSession();
        });
        
        // 历史记录按钮事件 - 移除点击事件，使其仅显示历史记录列表
        // historyBtn.addEventListener('click', function() {
        //     showHistorySessions();
        //     historyModal.style.display = 'flex';
        // });
        
        // 关闭历史记录弹窗
        // closeHistoryModal.addEventListener('click', () => {
        //     historyModal.style.display = 'none';
        // });
        
        // 点击弹窗外部关闭
        // window.addEventListener('click', (e) => {
        //     if (e.target === historyModal) {
        //         historyModal.style.display = 'none';
        //     }
        // });

        // 在页面加载时检查是否有会话ID参数
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化历史记录列表
            updateHistoryList();
            
            // 更新所有消息的retry按钮处理
            updateRetryButtonHandler();
            
            // 隐藏导出按钮
            updateExportButtonsVisibility(false);
            
            // 检查窗口大小并适配移动端
            initMobileMenu();
            
            // 初始化树结构
            if (messageTree && messageTree.nodes.length > 0) {
                messageTree.initD3Tree();
                messageTree.render();
            }
            
            // 检查并恢复主题设置
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme === 'dark') {
                document.body.classList.add('dark-mode');
                document.getElementById('lightIcon').style.display = 'none';
                document.getElementById('darkIcon').style.display = 'block';
            }
        });

        // 添加自动保存功能
        let autoSaveTimeout = null;
        
        // 在页面加载时初始化自动保存
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化历史记录列表
            updateHistoryList();
            
            // 设置自动保存
            setupAutoSave();
            
            // 更新所有消息的retry按钮处理
            updateRetryButtonHandler();
            
            // 隐藏导出按钮
            updateExportButtonsVisibility(false);
            
            // 检查窗口大小并适配移动端
            initMobileMenu();
            
            // 初始化树结构
            if (messageTree && messageTree.nodes.length > 0) {
                messageTree.initD3Tree();
                messageTree.render();
            }
            
            // 检查并恢复主题设置
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme === 'dark') {
                document.body.classList.add('dark-mode');
                document.getElementById('lightIcon').style.display = 'none';
                document.getElementById('darkIcon').style.display = 'block';
            }
        });

        // 导出模态窗口和导出功能
        let currentExportContent = "";

        // 显示导出模态窗口
        function showExportModal(content) {
            // 保存当前内容
            currentExportContent = content;
            
            // 清除HTML标签，获取纯文本内容用于预览
            const cleanText = content.replace(/<[^>]*>/g, '');
            
            // 更新预览内容
            const previewElement = document.getElementById('exportPreview');
            previewElement.textContent = cleanText;
            
            // 显示模态窗口
            const modal = document.getElementById('exportModal');
            modal.style.display = 'block';
            
            // 聚焦到文件名输入框
            document.getElementById('exportFilename').focus();
        }

        // 关闭导出模态窗口
        function closeExportModal() {
            document.getElementById('exportModal').style.display = 'none';
            currentExportContent = "";
        }

        // 执行导出文件
        function exportFile() {
            const filename = document.getElementById('exportFilename').value.trim() || "润色结果";
            const formatElements = document.getElementsByName('format');
            let format = "txt";
            
            // 获取选择的文件格式
            for (let i = 0; i < formatElements.length; i++) {
                if (formatElements[i].checked) {
                    format = formatElements[i].value;
                    break;
                }
            }
            
            // 清除HTML标签
            const cleanText = currentExportContent.replace(/<[^>]*>/g, '');
            
            // 根据选择的格式导出文件
            if (format === "txt") {
                downloadTxtFile(cleanText, filename);
            } else {
                // 其他格式需要服务器端处理
                serverExport(cleanText, filename, format);
            }
            
            // 关闭模态窗口
            closeExportModal();
        }

        // 下载TXT文件（客户端处理）
        function downloadTxtFile(content, filename) {
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename + '.txt';
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            
            setTimeout(() => {
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }, 100);
        }

        // 服务器端导出其他格式
        function serverExport(content, filename, format) {
            // 创建JSON数据
            const data = {
                text: content,
                filename: filename,
                format: format
            };
            
            // 使用fetch API发送JSON数据
            fetch('/export', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('导出失败');
                }
                return response.blob();
            })
            .then(blob => {
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename + '.' + format;
                document.body.appendChild(a);
                a.click();
                
                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            })
            .catch(error => {
                console.error('导出错误:', error);
                alert('导出失败，请重试');
            });
        }

        // 在文档加载完成后绑定事件处理函数
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定关闭按钮
            document.getElementById('closeExportModal').addEventListener('click', closeExportModal);
            document.getElementById('cancelExport').addEventListener('click', closeExportModal);
            
            // 绑定确认导出按钮
            document.getElementById('confirmExport').addEventListener('click', exportFile);
            
            // 点击模态窗口外部关闭
            const modal = document.getElementById('exportModal');
            window.addEventListener('click', (e) => {
                if (e.target === modal) {
                    closeExportModal();
                }
            });
            
            // 绑定回车键提交
            document.getElementById('exportFilename').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    exportFile();
                }
            });
            
            // 阻止模态窗口内部点击冒泡到外层
            document.querySelector('.modal-content').addEventListener('click', (e) => {
                e.stopPropagation();
            });
            
            // 其他已有事件...
            updateRetryButtonHandler();
        });
    </script>
</body>
</html>